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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading text files (.txt) trouble

Status
Not open for further replies.

stevepuri

Programmer
Mar 30, 2001
24
0
0
US
Hey,

The following code tries to read a text file "myFile.txt" and store the contents of this file into a String variable called "strFileData" and then output this variable to standard output.

It does'nt work!

Why does this variable contain integers?
Where is the string contents of "myFile.txt"?

If anyone has another way of doing this then tell me!

Thanks,
Steve.


Code:
String strFileData = "";

try
{
	File file = new File("myFile.txt");
	FileReader fileReader = new FileReader(file);

	int data;

	while ((data = fileReader.read()) != -1)
	{
		System.out.write(data);
		strFileData += data;
	}

	fileReader.close();
}
catch (IOException io)
{

}

System.out.println(strFileData); // outputs rubbish!
 
Hi,

The reason why it isn't working is because it reads in an int instead of character :) fileReader.read() returns an int. So this is what you can do:-

import java.io.*;
public class test
{
public static void main(String[] args)
{
String fileData="";
String temp="";
try
{
FileReader fr = new FileReader("abc.txt");
BufferedReader br = new BufferedReader(fr);
temp = br.readLine();
while (temp != null)
{
if (fileData.equals(""))
fileData = temp;
else
fileData = fileData +"\n"+ temp;
temp = br.readLine();
}
System.out.println(fileData);
}
catch (IOException e)
{}
}
}

Regards,
Leon If you need additional help, you can email to me at zaoliang@hotmail.com I don't guaranty that I will be able to solve your problems but I will try my best :)
 
Hi,
Yes, you are reading integers, infact you are reading decimal ASCII codes. So if you want to use that original piece of code you have, just fix it like that:

String strFileData = "";
try
{
File file = new File("abc.txt");
FileReader fileReader = new FileReader(file);

int data;

while ((data = fileReader.read()) != -1)
{
System.out.write(data);
strFileData += (char)data;
}
fileReader.close();
}
catch (IOException io)
{
}

...So the only change to the original is char -cast. That casts the ASCII code to char (readable letter).
 
...System.out.print -method casts single character automatically, thats why it works in the loop.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top