Java: Read up to x chars from a file into array

1.6k views Asked by At

I want to read a text file and store its contents in an array where each element of the array holds up to 500 characters from the file (i.e. keep reading 500 characters at a time until there are no more characters to read).

I'm having trouble doing this because I'm having trouble understanding the difference between all of the different ways to do IO in Java and I can't find any that performs the task I want.

And will I need to use an array list since I don't initially know how many items are in the array?

3

There are 3 answers

0
Daniel Lubarov On BEST ANSWER

It would be hard to avoid using ArrayList or something similar. If you know the file is ASCII, you could do

int partSize = 500;
File f = new File("file.txt");
String[] parts = new String[(f.length() + partSize - 1) / partSize];

But if the file uses a variable-width encoding like UTF-8, this won't work. This code will do the job.

static String[] readFileInParts(String fname) throws IOException {
    int partSize = 500;
    FileReader fr = new FileReader(fname);
    List<String> parts = new ArrayList<String>();
    char[] buf = new char[partSize];
    int pos = 0;

    for (;;) {
        int nRead = fr.read(buf, pos, partSize - pos);
        if (nRead == -1) {
            if (pos > 0)
                parts.add(new String(buf, 0, pos));
            break;
        }
        pos += nRead;
        if (pos == partSize) {
            parts.add(new String(buf));
            pos = 0;
        }
    }
    return parts.toArray(new String[parts.size()]);
}

Note that FileReader uses the platform default encoding. To specify a specific encoding, replace it with new InputStreamReader(new FileInputStream(fname), charSet). It bit ugly, but that's the best way to do it.

1
talnicolas On

An ArrayList will definitely be more suitable as you don't know how many elements you're going to have.

There are many ways to read a file, but as you want to keep the count of characters to get 500 of them, you could use the read() method of the Reader object that will read character by character. Once you collected the 500 characters you need (in a String I guess), just add it to your ArrayList (all of that in a loop of course).

The Reader object needs to be initialized with an object that extends Reader, like an InputStreamReader (this one take an implementation of an InputStream as parameter, a FileInputStream when working with a file as input).

0
javaCity On

Not sure if this will work, but you might want to try something like this (Caution: untested code):

  private void doStuff() {
    ArrayList<String> stringList = new ArrayList<String>();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader("file.txt"));
        String str;
        int count = 0;
        while ((str = in.readLine()) != null) {
            String temp = "";
            for (int i = 0; i <= str.length(); i++) {
                temp += str.charAt(i);
                count++;
                if(count>500) {
                    stringList.add(temp);
                    temp = "";
                    count = 0;
                }
            }
            if(count>500) {
                stringList.add(temp);
                temp = "";
                count = 0;
            }

        }
    } catch (IOException e) {
        // handle
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}