Java:如何从.txt文件中将单独的文本行保存到字符串数组中?

时间:2016-03-04 00:50:59

标签: java arrays string file object

import java.util.*;
import java.io.*;

public class readFiles2 {

public static void main(String[] args) throws IOException{
    // TODO Auto-generated method stub

    BufferedReader reader = new BufferedReader(new FileReader("someFile.txt"));

    try{
        StringBuilder text = new StringBuilder();
        String readStringLine = reader.readLine();
        String[] lines= {};


        for(int i = 0; readStringLine != null; i++){
            readStringLine = reader.readLine();

            //Trying to save seperate lines of text in an array.
            lines[i] = readStringLine.toString();
        }

    }
    finally{
        reader.close();
    }


}

所以我要做的就是将单独的字符串行从.txt文件保存到String[]数组。我现在有点不知所措,并不知道我还能做些什么。

3 个答案:

答案 0 :(得分:1)

由于您不知道您的数组有多少字符串,您可能希望将字符串放在列表中并最后转换为数组:

String readStringLine;
List<String> lines = new ArrayList<String>();

while((readStringLine = reader.readLine()) != null) {
    lines.add(readStringLine);
}

String[] linesArray = lines.toArray(new String[lines.size()]);

修改:简化为使用while循环从阅读器收集行。

答案 1 :(得分:1)

ArrayList<String> line = new ArrayList<>(); FileReader file = new FileReader(file.txt); BufferedReader reader = new BufferedReader(file); while (reader.ready()) { line.add(reader.readLine()); reader.close(); file.close(); }

要访问,请使用line.get(i);其中i&gt; = 0且i&lt; = array.size

答案 2 :(得分:0)

使用autocloseable接口和Java 8流:

String [] stringsArray = null;
try(BufferedReader br = new BufferedReader(new FileReader("someFile.txt"))) {
    List<String> strings = new ArrayList<>();
    br.lines().forEach(c -> strings.add(c));
    stringsArray = strings.toArray(new String[strings.size()]);
}

您需要Java 8来运行此代码