Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opening file and reading strings from file

Status
Not open for further replies.

hedgracer

Programmer
Mar 21, 2001
186
US
I need to open a file and read the string object from the file. I realize that I need to use the java.io class but am confused about which method to use (something comparable to the ifstream in C++). Whatever is used needs to input a string object for parsing inside of the java program. I am looking for any suggestions that can be offered.

I also need to read the string object from the file and halt reading (and parsing) when the file reaches EOF. Is there anything comparable to eof and getline in Java? Once gain, I appreciate any suggestions offered.

Thanks in advance.

Dave Christman
 
BufferedReader in = null
try
{
in = new BufferedReader(new FileReader("myFile.txt"));
String line = in.readLine();
while (line != null)
{
// do something with the line
// ...
line = in.readLine();
}
}
catch (IOException eIO)
{
System.out.println("Failed to open file.");
}
finally
{
try { in.close(); } catch (Exception eClose) {}
}
 
first of all import the java.io.* package

the ntry the following code

System.out.print("Enter name of the file to read from: ");
String InpFile = read.GetString();

try {
File fileIn = new File(InpFile);

//Open the input file as a buffered input stream

BufferedReader fIn = new BufferedReader(new FileReader(fileIn));
// 'fileIn' is the name of the file you want to open
String line = fIn.readLine();

while
(line != null)
{

System.out.println(line);

line = fIn.readLine();
}

//Close the files (to flush the buffers)

fIn.close();
}
}// end try
catch (IOException e)
{
System.out.println("File not found! ");
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top