简体   繁体   English

在java中读取文本文件时的垃圾字符

[英]Junk characters while reading text file in java

I have a java which calls windows bat file which does some processing and generates the output file. 我有一个java调用windows bat文件,它执行一些处理并生成输出文件。
Process p = Runtime.getRuntime().exec("cmd /c "+filename);
Now when reading the file from following program. 现在从以下程序中读取文件。 ( filexists() is function which checks whether file exists or not). filexists()是检查文件是否存在的函数)。 Output file contains only single line 输出文件仅包含单行

if ( filexists("output.txt") == true)    
{   String FileLine; 
    FileInputStream fstream = new FileInputStream("output.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

    FileLine = br.readLine();
    fstream.close();
    filein.close();

}

Variable FileLine contains 3 junk charcters in the starting. 变量FileLine在起始时包含3个垃圾字符。 I also checked few other files in the progam and no file has this issue except for the fact it is created with Runtime function. 我还检查了progam中的其他几个文件,没有文件有这个问题,除了它是用Runtime函数创建的。
9087 . 9087
As you can see three junk characters are coming in the output file. 正如您所看到的那样,输出文件中会出现三个垃圾字符。 When opened with Notepad++, i am not able to see those junk characters. 用Notepad ++打开时,我无法看到那些垃圾字符。

Please suggest 请建议

This is happening because you have not mentioned the file encoding while creating your FileInputStream.Assuming your file is UTF-8 encoded, you need to do something like this 发生这种情况是因为在创建FileInputStream时没有提到文件编码。假设你的文件是UTF-8编码的,你需要做这样的事情

   new FileInputStream("output.txt, "UTF-8"));

Change the encoding as per the encoding of your file 根据文件的编码更改编码

That looks like the byte order mark for UTF-8 encoding. 这看起来像UTF-8编码的字节顺序标记。 See https://en.wikipedia.org/wiki/Byte_order_mark 请参阅https://en.wikipedia.org/wiki/Byte_order_mark

May be its an issue with file encoding. 可能是文件编码的问题。 Though I am not sure. 虽然我不确定。 Can you please try following piece of code and see if it works for you 您能否请尝试以下代码,看看它是否适合您

BufferedReader in = new BufferedReader(
new InputStreamReader( new FileInputStream("output.txt"), "UTF8"));

String str;

while ((str = in.readLine()) != null) {
  System.out.println(str);
}

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

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