1

I want to read my text file with new lines, for example, I have that txt file ;

I'm a paragraph. Click here to add your own text and edit me. It?s easy. Just click ?Edit Text? or double click me to add your own content and make changes to the font. Feel free to drag and drop me anywhere you like on your page. I?m a great place for you to tell a story and let your users know a little more about you.

This is a great space to write long text about your company and your services. You can use this space to go into a little more detail about your company. Talk about your team and what services you provide. Tell your visitors the story of how you came up with the idea for your business and what makes you different from your competitors. Make your company stand out and show your visitors who you are.

and I want to read that file as seems.

I tried this code:

FileReader fr = 
  new FileReader("C:\\Users\\pankaj\\Desktop\\test.txt"); 

int i; 
while ((i=fr.read()) != -1) 
  System.out.print((char) i); 
}

But it gets without newlines.

Is there any way to get text file with newlines?

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
Yusuf Şengün
  • 296
  • 1
  • 11

3 Answers3

0

You could do something like this:

try(BufferedReader br = new BufferedReader(new FileReader(pathToYourFile))) {
    String line = br.readLine();

    while (line != null) {
        // do something with your line, like printing it or appending to a StringBuilder
        System.out.println(line);
        line = br.readLine();
    }
}

Or check out the other possibilities from the answeres here or here.

maloomeister
  • 1,788
  • 1
  • 7
  • 13
0

You can use Scanner class

Scanner sc = new Scanner(file);       
while (sc.hasNextLine())  {
      System.out.println(sc.nextLine()); 
} 
jafarmlp
  • 1,049
  • 12
  • 11
0

You can use any Reader that supports readLine(), which reads the next line of the text without the ending line separator - but you can just add that using System.lineSeparator().

Another approach is to read all bytes in the file and convert that into a string. There are multiple utility methods in the java.nio.file.Files class. Example:

RandomAccessFile raf=new RandomAccessFile(yourFile,"r");
String text="";
for(String line=raf.readLine();line!=null;line=raf.readLine()){
text+=line+System.lineSeparator();
}

Example 2:

String text=Files.readString(yourPath);

Example 3:

String text=new String(Files.readAllLines(yourPath), StandardCharsets.UTF_8);
tibetiroka
  • 1,056
  • 2
  • 9
  • 17