1

I want every line in my textdoc to be assigned to a variable.

import java.io.*;
import static java.lang.System.*;

class readfile {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("filename");
            BufferedReader br = new Buffered(fr);
            String str;
            while ((str = br.readLine()) != null) {}
            br.close();
        } catch (IOException e) {
            out.println("file not found");
        }
    }
}
1
  • I suggest instead of assigning every line to a variable, you can create a list and store every line into the list. Later you can retrieve line string from the list when need them line by line. Commented May 31, 2015 at 16:11

4 Answers 4

2

I would suggest you create a List and store every line in a list like below:

 String str;
 List<String> fileText = ....;
 while ((str = br.readLine()) != null) {
     fileText.add(str);
 } 
Sign up to request clarification or add additional context in comments.

Comments

0

A Java 8 solution for creating a List of lines

 Path path = Paths.get("filename");
 List<String> lines = Files.lines(path).collect(Collectors.toList());

Comments

0

why do you want to add each line to a separate variable? It is better to add the lines to a list. Then you can access any line as you want.

In JDK 6 or below

List<String> lines = new ArrayList<String>();
while(reader.ready())
     lines.add(reader.readLine());

In JDK 7 or above

List<String> lines = Files.readAllLines(Paths.get(fileName),
                    Charset.defaultCharset());

Comments

0

I would do

 List<string> allText= new List<String>();
 While(str.hasNextLine){
    allText.add(str.nextLine);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.