我想從包中讀取.txt文件。要直接從文件所在的計算機上的位置讀取它,但是從它的包中它不會。我之前使用過類加載器,但如果這是答案,我不太確定如何使用它們。 這將打開文件並逐行讀取它。讀取包中的.txt文件
ReadTextFile.class
public void readFile(String fileLocation){
try{
FileInputStream fstream = new FileInputStream(fileLocation);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
這是我在其他類地說讀什麼文件。
ReadTextFile textFile;
textFile = new ReadTextFile();
textFile.readFile("src/com/game/level_" + level + ".txt");
如果我把它作爲eclipse外的jar文件運行,我得到這個錯誤。
Error: src\com\game\level_1.txt (The system cannot find the path specified)
我所有的類都在相同的包中,所以是.txt文件。 如何從包中讀取.txt文件。 感謝您的幫助。
「[...]從打包它不會。「精心闡述?怎麼了?錯誤? – OptimusCrime
對不起忘記了。現在加入。 – user3080274
OP可能是指從類路徑中讀取的字段,請查看[Class#getResourceAsStream(java.lang.String)](http://docs.oracle.com/javase/7/docs/api/java/lang/ Class.html#getResourceAsStream(java.lang.String)),並從''src/com/game/level_「+ level +」.txt「中刪除'src'' – A4L