Asked  7 Months ago    Answers:  5   Viewed   51 times

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of the text file:

1 62 4 55 5 6 77

I want to have it in an arraylist as [1, 62, 4, 55, 5, 6, 77]. How can I do it in Java?



You can use Files#readAllLines() to get all lines of a text file into a List<String>.

for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    // ...

Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files

You can use String#split() to split a String in parts based on a regular expression.

for (String part : line.split("\s+")) {
    // ...

Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String

You can use Integer#valueOf() to convert a String into an Integer.

Integer i = Integer.valueOf(part);

Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings

You can use List#add() to add an element to a List.


Tutorial: Interfaces > The List Interface

So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String part : line.split("\s+")) {
        Integer i = Integer.valueOf(part);

If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines().

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\s+")).flatMap(Arrays::stream)

Tutorial: Processing data with Java 8 streams

Tuesday, June 1, 2021
answered 7 Months ago

Use an URL instead of File for any access that is not on your local computer.

URL url = new URL("");
Scanner s = new Scanner(url.openStream());

Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow.

The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.

About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).

Here with some sample exception-handling:

try {
   URL url = new URL("");
   Scanner s = new Scanner(url.openStream());
   // read from your scanner
catch(IOException ex) {
   // there was some connection problem, or the file did not exist on the server,
   // or your URL was not in the right format.
   // think about what to do now, and put it here.
   ex.printStackTrace(); // for now, simply output it.
Thursday, June 3, 2021
answered 6 Months ago

What's the disadvantage of just creating a new BufferedReader to read from the top? I'd expect the operating system to cache the file if it's small enough.

If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific reason to. I mean, you could just read the whole thing into memory and then do the two passes on the result, but again that's going to be more complicated than just reading from the start again with a new reader.

Friday, June 18, 2021
answered 6 Months ago

One approach would be to use String.replaceAll():

File log= new File("log.txt");
String search = "textFiles/a\.txt";  // <- changed to work with String.replaceAll()
String replacement = "something/bob.txt";
//file reading
FileReader fr = new FileReader(log);
String s;
try {
    BufferedReader br = new BufferedReader(fr);

    while ((s = br.readLine()) != null) {
        s.replaceAll(search, replacement);
        // do something with the resulting line

You could also use regular expressions, or String.indexOf() to find where in a line your search string appears.

Saturday, June 19, 2021
answered 6 Months ago

Question is pretty vague, so I'll just list some options to look into:

1) Firstly, if this is a browser page, you can serve the html page on the server and request it from the client.

2) Alternatively, you can have a build step that replaces some variable value with the HTML file's contents. This will avoid the HTTP request of solution (1).

3) On the other hand, if this is a node (or electron) app, in addition to solution (2), you can use node's fs to access the HTML file.

4) Lastly, perhaps the simplest but least salable solution, put the HTML in a JS object. Unlike JSON, JS objects can support new lines; e.g.

let x = {
    str: `line 1
          line 2`

Though even if you want to use a JSON file, you could include escaped new liens n in strings.

Friday, September 3, 2021
Ujjawal Khare
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :