FileReader没有读取1stCharacter

use*_*227 1 java file-io

各位朋友,我正在制作一个程序,其中正在读取txt文件并显示输出.我正在使用FileReader和eclipse juno的编辑器.但是当我这样做时,我能够读取完整的txt文件,但不能读取第一个字符.例如,假设我们有txt文件,其中写有"斯巴达克斯自由",因此编译器必须在结果中显示整个字符串.而不是这个,它显示"斯巴达克斯的统治",因此没有显示第一个字符.这是我的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题,任何人都能帮我解决这个问题吗?

Pet*_*rey 6

你正在阅读第一个字符而忽略它

f2.read();
Run Code Online (Sandbox Code Playgroud)

删除此行,它将按您的意愿工作.

长度是以字节为单位的长度,而不是字符.在你的情况下它可能是相同的,但你应该读入一个byte []并使用它来构建String.

相反,我建议

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.
Run Code Online (Sandbox Code Playgroud)