Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileInputStream to a String

 
Raja Sam
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following logic to open a file:

Except what I want to do is not just print the file on the screen, but to take a particular line and store it to a String called test.

For example take line 35 in the text file and store that in the String called test.

Can someone please help me with this ?

// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;

java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);

int i;

while ((i=fileInputStream.read()) != -1)
{

System.out.write(i);
}

fileInputStream.close();
 
Ramesh Pramuditha Rathnayake
Ranch Hand
Posts: 178
2
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this..



 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15288
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like you're reading a text file. Especially if you're interested in reading the file line by line, then using a BufferedReader will be easier and faster than reading the file character by character.

Another problem is that you're directly casting bytes read from the file to characters. That only works if the file contains ASCII text (it might fail if the file actually contains text in another character encoding). I won't go into that though, it's a more advanced subject.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic