我有一個文本文件,我已經叫read_me2(link):如何閱讀包含文本和整數文件並保存整數數組中的列表
!This is for testing the ability to read a file
1 3
4 5
6 7
8 9
1
2
3
4
5 6 4
我想讀它,並存儲使用Java 8功能的整數列表中的數據。到目前爲止,我能夠做到,但以我認爲不理想的方式。你能給我一些幫助嗎?下面,就請找我的代碼:
//This is my package
package ReadAFile;
// Modified http://www.mkyong.com/java8/java-8-stream-read-a-file-line-by-line/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadAndStoreFileContents {
public static void main(String[] args) {
List<String> list2 = new ArrayList<>();
String fileName2 = "/Users/riccardo/Dropbox/A-Data/JavaSandBox/read_me2.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName2))) {
list2 = stream.
filter(line -> !line.startsWith("!")).
collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
// This will be certainly not optimal because I m reading the List a second time
List<Integer> intList = new ArrayList<>();
for(String string : list2){
for(String retval: string.split(" ")){
intList.add(Integer.valueOf(retval));
}
System.out.println(intList.toString());
}
}
}
謝謝您的時間,
裏卡多
這個問題更適合代碼審查:http://codereview.stackexchange.com/ – nickb