2014-02-24 44 views
0

我無法存儲文件中的值。替代讀文件方法

3 
10 2 
100 35 
5 4 
17 20 3 5 
6 10 
6 9 12 15 18 21 24 27 30 33 

我希望將第一行存儲爲整數,將其他行作爲單獨的int數組存儲。

BufferedReader br = null; 
    try { 
     String sCurrentLine; 
     br = new BufferedReader(new FileReader("candy.dat")); 
     while ((sCurrentLine = br.readLine()) != null) { 
      System.out.println(sCurrentLine); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null)br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

有沒有另外一種方法呢?謝謝

編輯:基本上第一個整數(在這個例子中是3)將表示有多少測試用例要遵循。每個測試用例後面將有兩行。所以第一個測試案例是[10,2] [100,35]。

編輯2:我設法解決我的問題,如果有人想知道。 這是我的代碼

Scanner sc = new Scanner(new File("candy.dat")); 
    String testCase = sc.nextLine(); 
    String[] numOfCandy = new String[0]; 
    String[] NK = new String[0]; 

    for (int i = 0; i < Integer.parseInt(testCase); i++) { 
     System.out.println("test case " + (i+1)); 
     NK = sc.nextLine().split(" "); 
     numOfCandy = sc.nextLine().split(" "); 

     //System.out.println(NK[0] + " " + NK[1]); 
     //System.out.println(numOfCandy[0] + " " + numOfCandy[1]); 

     find(NK[0], NK[1], numOfCandy); //method to solve problem 
    } 

我第一次存儲的測試用例價值,這是3,說了多少次循環運行。

我實例化了2個字符串數組供以後使用。

在for循環中,我讀取下一行並將其拆分成字符串數組NK,然後將該行存儲到numOfCandy中。

從那裏,我能夠成功地從數組中檢索數據來解決我的問題。

+1

你的問題不是很清楚。你有代碼到某一點,但似乎你沒有嘗試去解決方案。你實際上堅持了什麼? –

+0

如果我在你的鞋子裏,我會把這些數據存儲在一個定義良好的結構中,然後作爲JSON字符串持久/恢復。 2C。 – Leo

回答

0

回答,現在,沒有時間,沒有腦...很酷的態度:`

public static void main() throws Exception { 
    final Scanner scanner = new Scanner(new File(file_str)); 
    while (scanner.hasNextLine()) { 
     if (scanner.hasNextInt()) { 
      final int nb = scanner.nextInt(); 
      System.err.println(nb); 
      final String[] str = scanner.findInLine(".*").split(" "); 
      System.err.println("-----" + str); 
     } 

    } 
    System.err.println("END"); 
    scanner.close(); 
}