2014-01-12 79 views
0

我想從包中讀取.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文件。 感謝您的幫助。

+0

「[...]從打包它不會。「精心闡述?怎麼了?錯誤? – OptimusCrime

+0

對不起忘記了。現在加入。 – user3080274

+0

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

回答

0

這應該工作:

package com.game; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

public class MyClass { 

    public static void main(String... args) throws IOException { 
     new MyClass().readLevel(1); 
    } 

    private void readLevel(int i) throws IOException { 
     try (InputStream is = getClass().getClassLoader() 
       .getResourceAsStream("com/game/level_" + i + ".txt"); 
       BufferedReader br = 
       new BufferedReader(new InputStreamReader(is))) { 
      String line; 
      while(null != (line = br.readLine())) { 
       System.out.println(line); 
      } 
     } 
    } 
} 

輸出是(樣品文本內容)

level 1 
hello 

如果沒有,那麼請提供Minimal, Complete, and Tested Code Sample

+0

絕對完美!非常感謝你,因爲這已經讓我感動了這麼久! – user3080274

+0

很酷,現在我只是好奇,想知道它是如何不工作... – A4L