Reputation: 493
Hello friends, I am making a program in which a txt file is being read and shown for output. I am using FileReader and the editor of eclipse juno for this. But while I am doing this, I am able to read the full txt file but not the first character. For example, say we have txt file in which: "Freedom of Spartacus" is written, so the compiler should have to show in result the whole string. Instead of this, it is showing "reedom of Spartacus" thus not showing the first character. Here is my code:
package file;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class O
{
public static void main(String[] args) throws IOException
{
File f1=new File ("tj.txt");
FileReader f2=new FileReader(f1);
f2.read();
System.out.println("Starting TO Read");
long size=f1.length();
char[] x=new char[(int)size];
f2.read(x);
f2.close();
String s1=new String(x);
System.out.println(s1);
}
}
What is wrong with my code and can any one help me with this?
Upvotes: 1
Views: 235
Reputation: 533500
You are reading the first character and ignoring it here
f2.read();
Remove this line and it will work as you want.
The length is the length in bytes, not characters. It may be the same in your case, but you should read into a byte[] and use that to build the String.
Instead I suggest
FileInputStream fis = new FileInputStream("tj.txt");
byte[] bytes = new bytes[(int) fis.getChannel().size()];
fis.read(bytes);
fis.close();
String s = new String(bytes, "UTF-8"); // or your preferred encoding.
Upvotes: 6
Reputation: 109001
You are reading/skipping that character yourself by calling f2.read()
on the third line in your main()
.
Upvotes: 2
Reputation: 468
With the first f2.read()
you read the first character but you don't store it anywhere.
Upvotes: 2
Reputation: 24316
Because of this line:
f2.read();
You have already gone passed the F
. You want this code:
public static void main(String[] args) throws IOException
{
File f1=new File ("tj.txt");
FileReader f2=new FileReader(f1);
System.out.println("Starting TO Read");
long size=f1.length();
char[] x=new char[(int)size];
f2.read(x);
f2.close();
String s1=new String(x);
System.out.println(s1);
}
Upvotes: 2