简体   繁体   中英

Read in file and store into a dynamically allocated string array

Beginner Java programmer here. I have searched for a while on the interwebs without much success.

I need to read in a text file and store each line into a string array. However I do not know how big the text file will be thus I was trying to figure out a easy way to dynamically allocate the size of the string array. I didn't know if there was a handy tool already in the Java library I could use. I was thinking maybe counting the total # of lines in the file first, then allocating the string array, but I also didn't know the best way to do that.

Thank you for any input!

You could use an ArrayList and not worry about sizing:

List<String> fileLines = new ArrayList<String>();

try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
    String line;
    while ((line = br.readLine()) != null)
        fileLines.add(line);
}

fileLines could get pretty big, but if you're okay with that then this is an easy way to get started.

Define an array-list which does not require a fixed length, as you can add or remove as many elements as you wish:

    List<String> fileList = new ArrayList<String>();
    //Declare a file at a set location:
    File file = new File("C:\\Users\\YourPC\\Desktop\\test.txt");
    //Create a buffered reader that reads a file at the location specified:
    try (BufferedReader br = new BufferedReader(new FileReader(file)))
    {
        String line;
        //While there is something left to read, read it:
        while ((line = br.readLine()) != null)
            //Add the line to the array-list:
            fileList.add(line);
    }catch(Exception e){
        //If something goes wrong:
        e.printStackTrace();
    }

    //Determine the length of the array-list:
    int listTotal = fileList.size();
    //Define an array of the length of the array-list:
    String[] fileSpan = new String[listTotal];

    //Set each element index as its counterpart from the array-list to the array:
    for(int i=0; i<listTotal; i++){

        fileSpan[i] = fileList.get(i);
    }

If you only want a working program (and not practice in coding and debugging) in Java8+:

 String[] ary = java.nio.file.Files.readAllLines(Paths.get(filename)).toArray(new String[0]);
 // substitute the (Path,Charset) overload if your data isn't compatible with UTF8
 // if a List<String> is sufficient for your needs omit the .toArray part

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM