2012-04-29 69 views
0

我正在製作一個使用文本文件的程序。我需要這樣做,以便程序可以使用其jar文件從另一臺計算機上運行。問題是,我無法找到正確的文件路徑到文本文件。我試過使用getResource(),但它仍然不能正常工作。代碼如下:無法在Netbeans項目中獲取文件路徑

public class Params { 

    public static void init() { 

     hsChartSuited = new int[13][13]; 

     file = new File(Params.class.getResource("HandStrengthDataSuited.txt").getFile()); 

     try { 
      Scanner input = new Scanner(file); 
      for (int i = 0; i < hsChartSuited.length; i++) { 
       for (int j = 0; j < hsChartSuited[i].length; j++) { 
        hsChartSuited[i][j] = Integer.parseInt(input.next()) - 20; 
       } 
      } 
     } catch (FileNotFoundException e) { 
      System.out.println("File not found"); 

     } 
} 

HandStrengthDataSuited.txt是在我的項目的src文件夾中的文件。它也位於文件夾之外,也位於項目的主目錄中。我試着打印文件的絕對路徑,這就是我得到:

/Users/MyUsername/file:/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/dist/HoldEm.jar!/holdem/HandStrengthDataSuited.txt 

,我需要得到的文件路徑是

/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/holdem/HandStrengthDataSuited.txt 

有誰知道問題是什麼嗎?

回答

0

如果你的文件是在src文件夾,

class Tools { 
    public static InputStream getResourceAsStream(String resource) 
     throws FileNotFoundException 
     { 
     String stripped = resource.startsWith("/") ? resource.substring(1) : resource; 
     InputStream stream = null; 
     ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
     if (classLoader != null) { 
      stream = classLoader.getResourceAsStream(stripped); 
     } 
     if (stream == null) { 
      stream = Tools.class.getResourceAsStream(resource); 
     } 
     if (stream == null) { 
      stream = Tools.class.getClassLoader().getResourceAsStream(stripped); 
     } 
     if (stream == null) { 
      throw new FileNotFoundException("Resource not found: " + resource); 
     } 
     return stream; 
    } 
} 

用途:

reader = new BufferedReader(new InputStreamReader(getResourceAsStream("org/paulvargas/resources/file.txt"), "UTF-8")); 
+0

這樣,我取代''組織/ paulvargas /資源/ file.txt'的src /撲克/ HandStrengthDataSuited .txt「呢? – RaysonK

+0

只有'holdem/HandStrengthDataSuited.txt'如果src不是java數據包。 –