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?

2

3 Answers 3

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

I can mistake, but I think Charset.forName("Windiws-1251"), rather than Charset.forName("Cp1251"). Or both will be right?
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;
}
}

Comments

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

4 Comments

I'm sorry, but how? I mean, how can I load a text file in ArrayList? And can I work with ArrayList using regex?
@linuxedhorse You can work with lists in (almost) the same way as with arrays. You can also convert lists to arrays if you prefer.
@linuxedhorse, where exactly are you using regex in your current code?
I'm using regex in method in class, where FileLoader() is, and I'm working with the last one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.