space are coming between char when reading file in java

时间:2018-03-25 18:58:44

标签: java

here is the code it seems to be write but output is quite strange .

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 simple text file
output console

2 个答案:

答案 0 :(得分:1)

Most likely your file has not "UTF-8" encoding. You can use InputStreamReader to specify encoding or change file encoding to UTF-8

答案 1 :(得分:0)

The most likely cause is that you have saved the text file in Notepad as "Unicode" (UCS-2 encoding), and you are reading the file using your system default character set encoding. UCS-2 uses two bytes per character, but the FileReader uses system default encoding which assumes one byte per character on your particular PC.

Either save it as "ANSI" in Notepad, or open it in Java using UCS-2 or UTF-16 encoding:

in = new InputStreamReader(new FileInputStream("myFile.txt"), StandardCharsets.UTF_16);
相关问题