3

我怎样才能做到这一点?

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

或者

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

我将在getFile()方法中编写什么代码?

4

2 回答 2

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;

}
于 2012-12-20T07:04:19.903 回答
3

哟可以这样做

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

输出(我的 Eclipse 测试)

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

但它并不总是有效。如果你的资源在罐子里怎么办?你会得到

 java.lang.IllegalArgumentException: URI is not hierarchical
于 2012-12-20T06:59:49.867 回答