简体   繁体   English

txt文件开头的3个字符

[英]3 characters at the start of txt file

I'm trying to make a program that reads textfiles. 我正在尝试制作一个读取文本文件的程序。 I tried this code and it almost works but the output starts with these 3 characters  我尝试了这段代码,它几乎可以正常工作,但是输出以这3个字符开头?
How do I write so it doesn't output them? 我该怎么写,所以它不输出?

 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 + "'");
    }

It's commonly called a BOM (Byte Order Marker) that you can find in files encoded in UTF-8. 您通常可以在以UTF-8编码的文件中找到BOM(字节顺序标记)。 Here you can find a solution to read a file in utf-8: reading text file with utf-8 encoding using java 在这里,您可以找到一种读取utf-8中文件的解决方案: 使用java以utf-8编码读取文本文件

see if this works (using Scanner) 查看是否可行(使用扫描仪)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM