我该怎么做?
File myFile = getFile(this.getClass.getResourceAsStream("test.txt"))
或者
File myFile = getFile(this.getClass.getResource("test.txt"))
在getFile()
方法中,我需要编写什么代码?
我该怎么做?
File myFile = getFile(this.getClass.getResourceAsStream("test.txt"))
或者
File myFile = getFile(this.getClass.getResource("test.txt"))
在getFile()
方法中,我需要编写什么代码?
你可以这样做
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
以下是函数内容:
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
会打开一个流到构造函数中指定的绝对路径所指向的文件。您可以将其作为函数参数传递,以避免硬编码。 - Santosh