I have a question for JAVA.

Asked 2 years ago, Updated 2 years ago, 149 views

package Ex;

import java.io.*;

public class fre {

    public static void main(String[] args) throws IOException {
        FileInputStream fi = null;
        InputStreamReader in = null;
//      fi = newFileInputStream ("fileEx.txt"); // save as fileEx.txt ANSI
//      //      in = new InputStreamReader(fi, "MS949"); 

                fi = newFileInputStream ("fileEx1.txt");// save as fileEx1.txt UTF-8
        in = new InputStreamReader(fi, "UTF-8"); 
        int ch;

        while((ch = fi.read()) !=-1 ){
            System.out.print((char)ch); 
        }
        fi.close();
    }
}

File input and output. I wanted to print out the text entered in the file in the console window, but it keeps showing up in alien languages.

fileEx.txt (saved as ANSI)

File Reader File Writer
fileReader fileWriter
Java Test

FileEx.txt is saved as above and printed in the console window

Æ??? ¸®´? Æ??? ¶?????
fileReader fileWriter
Java Test

It's printed out like above. I think I have a wrong idea about the encoding system, so it's easier I did it in the uft-8 format.

fileEx1.txt (saved as UTF-8)

Java Practice "utf-8" Format

FileEx1.txt is saved as above and printed in the console window

??¿????°? ??°??? "utf-8"??????

It says "La. I don't know why I can't print it out in Korean when it seems like there's nothing wrong. ㅠ<

fileinputstream inputstreamreader

2022-09-21 15:58

2 Answers

Try wrapping it around a buffered reader.

    public static void main(String[] args) throws IOException {
        FileInputStream fi = null;
        InputStreamReader in = null;

        fi = newFileInputStream ("fileEx1.txt");// save as fileEx1.txt UTF-8
        in = new InputStreamReader(fi, "UTF-8");
        BufferedReader br  = new BufferedReader(in);

        int ch;

        while ((ch = br.read()) != -1) {
            System.out.print((char) ch);
        }
        fi.close();
    }


2022-09-21 15:58

Please specify file encoding as shown below and run it.

import java.io.*;

public class Test {
  public static void main(String[] args) throws IOException {
    FileInputStream fi = null;
    InputStreamReader in = null;

    fi = newFileInputStream ("fileEx1.txt");// save as fileEx1.txt UTF-8
    in = new InputStreamReader(fi, "UTF-8");
    BufferedReader br  = new BufferedReader(in);

    int ch;
    while ((ch = br.read()) != -1) {
      System.out.print((char)ch);
    }

    fi.close();
  }
}

rm *.class ; javac Test.java ; java -cp . -Dfile.encoding=UTF8 Test


2022-09-21 15:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.