1

您好朋友,我正在制作一个程序,其中正在读取并显示一个 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);
    }
}

我的代码有什么问题,有人可以帮助我吗?

4

5 回答 5

6

您正在阅读第一个字符并在此处忽略它

f2.read();

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

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

相反,我建议

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.
于 2013-07-19T13:22:25.440 回答
2

删除第一个

f2.read();

线

于 2013-07-19T13:22:55.977 回答
2

因为这条线:

f2.read();

你已经通过了F。你想要这个代码:

 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);

    }
于 2013-07-19T13:23:10.800 回答
2

使用第f2.read()一个字符时,您会读取第一个字符,但不会将其存储在任何地方。

于 2013-07-19T13:23:14.853 回答
2

f2.read()您正在通过调用main().

于 2013-07-19T13:23:38.483 回答