java文件读取问题

java文件读取问题,java,file-io,Java,File Io,在我的java应用程序中,我必须读取一个文件。我所面临的问题是,在读取文件后,结果是不可读的格式。这意味着会显示一些ascii字符。这意味着没有一个字母是可读的。我怎样才能让它显示出来 // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("c:\\hello.txt"); // Get

在我的java应用程序中,我必须读取一个文件。我所面临的问题是,在读取文件后,结果是不可读的格式。这意味着会显示一些ascii字符。这意味着没有一个字母是可读的。我怎样才能让它显示出来

 // Open the file that is the first
        // command line parameter

        FileInputStream fstream = new FileInputStream("c:\\hello.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println(strLine);
        }
        // Close the input stream
        in.close();
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

您必须采用这种方式来处理:-

BufferedReader br = new BufferedReader(new InputStreamReader(in, encodingformat));

编码格式
-根据遇到的编码问题类型进行更改

示例:UTF-8UTF-16。。。不久


有关更多信息,请参阅此

可能您有编码错误。用于InputStreamReader的构造函数使用默认字符编码;如果您的文件包含超出ASCII范围的UTF-8文本,您将得到垃圾。此外,您不需要DataInputStream,因为您没有从流中读取任何数据对象。请尝试以下代码:

FileInputStream fstream = null;
try {
    fstream = new FileInputStream("c:\\hello.txt");
    // Decode data using UTF-8
    BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String strLine;
    // Read File Line By Line
    while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        System.out.println(strLine);
    }
} catch (Exception e) {// Catch exception if any
    System.err.println("Error: " + e.getMessage());
} finally {
    if (fstream != null) {
        try { fstream.close(); }
        catch (IOException e) {
            // log failure to close file
        }
    }
}

由于您不知道文件所使用的编码,请使用检测文件所使用的编码,然后按照其他人的建议使用该编码读取文件。这不是100%的傻瓜,但适用于您的场景


另外,不需要使用数据输入流。

您得到的输出是一个ascii值,因此您需要在打印前将其键入cast(转换为字符或字符串)。希望这有助于解决我的问题。我不知道怎么做。我将hello.txt内容复制到另一个文件并运行java程序。我能读所有的信。不知道有什么问题。

hello.txt的内容是什么,输出显示什么?似乎是编码问题。hello.txt是怎么写的?其他文本文件是否也会出现同样的问题?请检查文件编码是否与系统编码一致。Java应该使用默认编码。我无法在此处显示输出..这就是我无法附加的原因..我的意思是它无法粘贴。这似乎是一些编码问题。我在文件中使用了许多前后斜杠。
hello.txt
的编码是什么?你怎么知道该文件是UTF-8格式的?@buruzaemon:是的,因为没有提到此人的编码类型问题。这就是我提到基本格式为“UTF-8”的原因。基于他的格式问题,他必须相应地进行更改。从技术上讲,这是他必须处理的。我的答案是“-1”,有什么不对?你不知道。但是这个源代码片段建议您需要指定它。我不知道否决投票的原因,但可能是因为您的回答措辞好像UTF-8是唯一可以使用的编码。朋友根据您的输入,我已从“UTF-8”更改为
encodingformat
。我建议使用一些UTIL来实现这一点。例如,在commons io中有IOUtils.readLines(inputStream,encoding)和IOUtils.Closequiely(someSource)@PetrGladkikh-是的,像commons io这样的UTIL是好的。谢谢你提到这件事。