2016-11-10 107 views
-2

所以我有一個數組int []數字= {1,2}; 但我想1,2被刪除,並用txt文件中的數字替換。 我可以看到用這種方法控制檯從文件中的數字:如何將整數從.txt文件保存到數組中?

public String[] readLines(String filename) throws IOException { 
    FileReader fileReader = new FileReader(filename); 
    BufferedReader bufferedReader = new BufferedReader(fileReader); 
    List<String> lines = new ArrayList<String>(); 
    String line = null; 
    while ((line = bufferedReader.readLine()) != null) { 
     lines.add(line); 
    } 
    bufferedReader.close(); 
    return lines.toArray(new String[lines.size()]); 
} 

public static void testFileArrayProvider() throws IOException { 
    algo1 fap = new algo1(); 
    String[] lines = fap 
      .readLines("D:/Users/XXX/workspace/abc/src/abc1/Filename123"); 
    for (String line : lines) { 
     System.out.println(line); 
    } 
} 

現在我需要將它們保存在數組中。如何? XD THX傢伙

+3

你能給你的文件內容的例子嗎?數字是如何分開的? –

+0

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – tnw

+0

number,next line,number,nextline。 SO 1每行數字 –

回答

2

這應該工作:

// In your case this is already populated 
    String[] lines = new String[] {"123", "4567"}; 


    // Easier to work with lists first 
    List<Integer> results = new ArrayList<>(); 
    for (String line : lines) { 
     results.add(Integer.parseInt(line)); 
    } 

    // If you really want it to be int[] for some reason 
    int[] finalResults = new int[results.size()]; 

    for (int i = 0; i < results.size(); i++) { 
     finalResults[i] = results.get(i); 
    } 

    // This is only to prove it worked 
    System.out.println(Arrays.toString(finalResults)); 

在Java-8,你可以把它縮短到

int[] finalResults = Arrays.stream(lines).mapToInt(Integer::parseInt).toArray(); 
+2

在java 8中,'int [] finalResults = Arrays.stream(lines).mapToInt(Integer :: parseInt).toArray();' – bradimus

+0

@bradimus謝天謝地java8 – DejaVuSansMono

+0

@bradimus更好。您應該將其作爲正確答案發布。 –

相關問題