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

ただし、常に機能するとは限りません。リソースがjarファイルにある場合はどうなりますか?あなたは得るでしょう

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