将文件内容拆分为ArrayList

时间:2016-02-05 08:14:12

标签: java

我有一个文件,我可以阅读它的内容。现在我想将每个单独的行分别拆分成一个arrayList并且不能成功。

这是我到目前为止所拥有的

try {
        input = new FileInputStream(test);


        byte testContent[] = new byte[(int) test.length()];
        input.read(testContent);


        String testFile = new String(testContent);
        System.out.println(testFile);

    }

文件内容的示例如下,

0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0 0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,1 0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,1 0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1 0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,1

我希望上面的内容像

一样

[0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0] [0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,1] [0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,1] [0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1] [0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,1]

提前感谢您提供任何帮助

4 个答案:

答案 0 :(得分:1)

Files.readAllLines()

怎么样?
List<String> lines = Files.readAllLines(new File(test).toPath());

如果您使用的是Java 7,则需要此版本:

List<String> lines = Files.readAllLines(new File(test).toPath(), StandardCharsets.UTF_8);

答案 1 :(得分:0)

使用String#split()

String[] strings= testFile.split("\\r?\\n"); 
List<String> list = Arrays.asList(strings);

您可以从此问题获得有关此方法的更多详细信息 How to split a string in Java

答案 2 :(得分:0)

String [] lines = testFile.split("\\r?\\n");

答案 3 :(得分:0)

您可以尝试这样的事情:

BufferedReader br = new BufferedReader(new FileReader(yourFile));
List<String[]> listOfArrays = new ArrayList<String[]>();

String nextLine;
while((nextLine = br.readLine()) != null){

    String[] lineArray = nextLine.split(",");
    listOfArrays.add(lineArray);

}