将资源/流转换为文件

3

我该怎么做?

File myFile = getFile(this.getClass.getResourceAsStream("test.txt"))

或者

File myFile = getFile(this.getClass.getResource("test.txt"))

getFile()方法中,我需要编写什么代码?


使用 BufferedReader?还是有更好的想法? - user1917885
类路径资源通常不是文件(在开发之外),因此您需要确保该文件未打包在存档中。 - McDowell
2个回答

4

你可以这样做

    File f = new File(this.getClass().getResource("test.txt").toURI());
    System.out.println(f);

输出(我的Eclipse测试)

D:\workspace1\x\target\classes\text.txt

但它并不总是有效。如果你的资源存在于一个jar包中,你将会收到

 java.lang.IllegalArgumentException: URI is not hierarchical

有没有办法让它在JAR文件内也能正常工作? - Max

4

以下是函数内容:

public File getFile(FileInputStream inStream){

File file =new File("file.txt");
OutputStream outStream = null;
outStream = new FileOutputStream(file);

byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes 
            while ((length = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0, length);

            }


            outStream.close();

return file;

}

FileOutputStream会首先将其写入由File提供的位置吗? - user1917885
FileOutputStream会打开一个流到构造函数中指定的绝对路径所指向的文件。您可以将其作为函数参数传递,以避免硬编码。 - Santosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接