2014-10-29 68 views
-1

我想寫一個文件在目錄中,我的main.class也是。 這總是得到一個錯誤:JAVA:在類路徑中寫入文本文件?

File file = new File(main.class.getResourceAsStream("test.txt")); 

那是不是工作壓力太大:

File file = new File(getClass().getResource(AsStream)("me.test.test.txt")); 

它總是說,該構造文件(InputStream的)是不確定的。 任何想法?

Regards,

+0

爲什麼特意在這裏?您可以設置外部的,定義明確的目錄 – fge 2014-10-29 22:50:46

+1

通常您不能寫入類路徑。您的課程可能會駐留在只讀JAR文件中。 – lexicore 2014-10-29 22:52:02

+0

一般來說,你不能這樣做。 CLASSPATH的元素應該被視爲只讀。例如,考慮一個JAR或未解壓縮的WAR文件。 – EJP 2014-10-29 23:01:29

回答

1

你不能在這個流中寫入,它是一個InputStream。您應該根據getResource(「test.txt」)提供的路徑創建FileOutpuStream。

如果該文件已經存在:

FileOutputStream file = new FileOutputStream(Main.class.getResource("/toto.txt").getFile()); 

如果它不存在:

FileOutputStream file = new FileOutputStream(Main.class.getResource("/").getFile() + "toto.txt"); 

但是,要小心,位置可以在一個jar文件,那麼就可以讀只要。

0

嘗試......

File file=(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())); 

文件對象表示在您main.class文件位於運行時的目錄。

之後創建新文件爲: 文件txtFile =新文件(文件,「myText.txt」);