1

How can I load .txt file into string array?

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;
    }
}

There is an issue with array's length, because I don't know how long my array will be. Of course i saw this question, but there is not an array of string. I need it, because I have to work with whole text, also with null strings. How can I load a text file into string array?

Community
  • 1
  • 1

3 Answers3

2

Starting with Java 7, you can do it in a single line of code:

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

If you need your data in a string array rather than a List<String>, call toArray(new Strinf[0]) on the result of the readAllLines method:

String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
  • I can mistake, but I think `Charset.forName("Windiws-1251")`, rather than `Charset.forName("Cp1251")`. Or both will be right? – linuxedhorse Dec 15 '13 at 23:31
  • @linuxedhorse [You are right, that's two synonyms for the same encoding](http://ru.wikipedia.org/wiki/Windows-1251#.D0.9A.D0.BE.D0.B4.D0.B8.D1.80.D0.BE.D0.B2.D0.BA.D0.B0_Windows-1251_.28.D1.81.D0.B8.D0.BD.D0.BE.D0.BD.D0.B8.D0.BC_CP1251.29) – Sergey Kalinichenko Dec 16 '13 at 03:17
0

You can use Collection ArrayList

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

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

Deepak
  • 1,641
  • 16
  • 28
0

Use List

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;
}
}
Anurag
  • 1,388
  • 2
  • 16
  • 31