Answer the question
In order to leave comments, you need to log in
How to read a line from a file in Java 7?
There is a text document in which there are only three lines, I need to read 1 line from it and put it in the String a variable;
the second line into the variable String b; and so on.
Or if you can then count the number of lines in the document and if there are 5 then create 5 String variables
and copy each line into a variable, that would be the best solution
Answer the question
In order to leave comments, you need to log in
You won't be able to create variables dynamically. Create an ArrayList and add strings to it.
To read line by line, you can use java.util.Scanner, it has convenient methods for reading a file line by line: hasNextLine and nextLine.
And what are those lines? It's not a config by any chance? If so, it's easier to use java.util.Properties, and store strings in a file in the format: <Parameter name>=<Value>
package ru.toster.java.q261000;
import java.io.*;
import java.util.*;
public class MainQ261000 {
public static void main(String[] args) {
String demoFile = "aaaaaaaaa\nbbbbbbbbbbbb\nccccccccccccccccc";
Reader r = new StringReader(demoFile);
// Reader r = new FileReader("FileWithTextLines.txt");
List<String> lines = new ArrayList<String>();
Scanner s = new Scanner(r);
try {
while(s.hasNextLine()) {
lines.add(s.nextLine());
}
} finally {
s.close();
}
for (String line : lines) {
System.out.println(line);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question