在java中读取文件时,字符之间有空格
这里是代码,它似乎是写的,但输出是非常奇怪的在java中读取文件时,字符之间有空格,java,Java,这里是代码,它似乎是写的,但输出是非常奇怪的 import java.io.*; public class Main { public static void main(String args[]){ FileReader in = null; try{ in = new FileReader("myFile.txt"); int c; while ((c = in.read()) !
import java.io.*;
public class Main {
public static void main(String args[]){
FileReader in = null;
try{
in = new FileReader("myFile.txt");
int c;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
}catch(IOException ie){
ie.printStackTrace();
}finally{
try{
if(in!=null){
in.close();
}
}catch(IOException ie){
ie.printStackTrace();
}
}
}
}
myFile.txt
输出
您的文件很可能没有“UTF-8”编码。您可以使用InputStreamReader指定编码或将文件编码更改为UTF-8最有可能的原因是您在记事本中将文本文件保存为“Unicode”(UCS-2编码),并且您正在使用系统默认字符集编码读取文件。UCS-2每个字符使用两个字节,但FileReader使用系统默认编码,即在特定PC上每个字符使用一个字节 在记事本中将其另存为“ANSI”,或使用UCS-2或UTF-16编码在Java中打开:
in = new InputStreamReader(new FileInputStream("myFile.txt"), StandardCharsets.UTF_16);
请附上文本文件(不是文件的屏幕截图)。