在字符串数组中加载.text文件

时间:2013-12-15 13:02:33

标签: java arrays string file-io

如何将.txt文件加载到字符串数组中?

private void FileLoader() {
    try {
        File file = new File("/some.txt");
        Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
            //Obviously, exception
            int i = 0;
        while (sc.hasNextLine()) {
        morphBuffer[i] = sc.nextLine();
        i++;
            //Obviously, exception  
        }
        sc.close();
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "File not found: " + e);
        return;
    }
}

数组的长度存在问题,因为我不知道数组的长度。 当然我看到this question,但没有数组的字符串。我需要它,因为我必须使用全文, null字符串。 如何将文本文件加载到字符串数组中?

3 个答案:

答案 0 :(得分:2)

从Java 7开始,you can do it in a single line of code

List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));

如果您需要字符串数组而不是List<String>中的数据,请在toArray(new Strinf[0])方法的结果上调用readAllLines

String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);

答案 1 :(得分:0)

您可以使用Collection ArrayList

while (sc.hasNextLine()) {
    list.add(sc.nextLine());
    i++;
        //Obviously, exception  
}

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

答案 2 :(得分:0)

使用清单

private void FileLoader() {
try {
    File file = new File("/some.txt");
    Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
    List<String> mylist = new ArrayList<String>();
    while (sc.hasNextLine()) {
        mylist.add(sc.nextLine());
    }
    sc.close();
} catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "File not found: " + e);
    return;
}
}