txt文件开头的3个字符

时间:2016-03-11 12:07:08

标签: java

我正在尝试创建一个读取文本文件的程序。我尝试了这个代码,它几乎可以工作,但输出从这3个字符开始 我怎么写,所以不输出它们?

 JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Select a text file");
    int Checker = chooser.showOpenDialog(null);
    File F = chooser.getSelectedFile();
    String line = null;

    try {
        FileReader fileReader = new FileReader(F);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        bufferedReader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Unable to open file '" + F + "'");
    } catch (IOException ex) {
        System.out.println("Error reading file '" + F + "'");
    }

2 个答案:

答案 0 :(得分:1)

它通常被称为BOM(字节顺序标记),您可以在以UTF-8编码的文件中找到它。 在这里,您可以找到在utf-8中读取文件的解决方案:reading text file with utf-8 encoding using java

答案 1 :(得分:0)

看看是否有效(使用扫描仪)

import java.io.*;
   import java.util.Scanner;
   import javax.swing.JFileChooser;

    public class ScanXan {
        public static void main(String[] args) throws IOException {


   JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Select a text file");
    int Checker = chooser.showOpenDialog(null);
    File F = chooser.getSelectedFile();


            Scanner s = null;

            try {
                s = new Scanner(new BufferedReader(new FileReader(F)));

                while (s.hasNext()) {
                    System.out.println(s.next());
                }
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        }
    }

参考:https://docs.oracle.com/javase/tutorial/essential/io/scanning.html