Meaningless Drivel is fun!
The moose likes Java in General and the fly likes FileInputStream to a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "FileInputStream to a String" Watch "FileInputStream to a String" New topic

FileInputStream to a String

Raja Sam

Joined: Jul 08, 2013
Posts: 1
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; fileInputStream = new + filename);

int i;

while (( != -1)


Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 178

Try this..

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15082

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: FileInputStream to a String
It's not a secret anymore!