35

I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.

The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?

Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?

I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Northener
  • 863
  • 4
  • 9
  • 14

5 Answers5

66

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

toolkit
  • 49,809
  • 17
  • 109
  • 135
  • 2
    Shouldn't the `bufferedReader.close()` be wrapped inside a `try {} finally {}` block? – LukeGT Apr 20 '13 at 04:01
  • @LukeGT- Yes, it should for production code. These example methods simply throw an exception. – toolkit Apr 20 '13 at 08:02
  • And these days it would be better to use a try-with-resources statement, rather than try-finally. – Slaw Mar 20 '20 at 04:38
41
import java.io.File;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import java.util.List;

// ...

Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();        
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Hélio Santos
  • 419
  • 4
  • 3
  • @Northener already mentioned that they have seen examples. This answer does not address any of the questions they asked. – allingeek Sep 26 '12 at 02:16
  • 6
    In Java 8, you can just call `Files.readAllLines(filePath)` which is equivalent to passing `StandardCharsets.UTF_8` as the charset. – Emil Laine Feb 15 '16 at 22:03
4

Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: http://commons.apache.org/io/api-release/index.html. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities.

0

You should be able to use forward slashes in Java to refer to file locations.

The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.

Toolkit's use of BufferedReader is probably what you need.

Ryan Thames
  • 3,204
  • 6
  • 31
  • 32
0

For completeness, another way to read all lines of a file1 as String[] is to use the Java 8+ BufferedReader.lines() method. Like this:

BufferedReader br ...
String[] lines = br.lines().toArray(String[]::new);

Note that since the lines() stream cannot tell the downstream methods how many lines there will be ahead of time, some temporary String arrays will need to be created. However, the implementation is designed to avoid unnecessary copying.


1 - You can use this approach with anything that you can wrap with a BufferedReader.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216