kenetik
kenetik

Reputation: 350

Java File Output not matching Console?

I have been working on this project that does some things, (which doesn't matter) and then outputs the results in the following format: ###x###x#### : or some integers separated by the lowercase letter x and then more integers, ending with the letter x.

I write the output to the console, data looks fine. I write to a text file, it comes out as either chinese characters, or garbled mess, when opened up in notepad. When I open the file up in notepad++ it comes out fine. I have tried every kind of output I can think of for java, and changed the encoding, but it all ends the same. What am I missing?

I know this is no where near optimal or how you are 'supposed to output' this is after many iterations of testing weird edge cases of casting and concatenating to see if anything works.

public static void printMap() throws IOException {
    //PrintWriter out = new PrintWriter("VertCover.txt", "UTF-8");
    //Charset charset = Charset.forName("UTF-8");
    //BufferedWriter out = new BufferedWriter(new FileWriter(new File("VertCover.txt")));
    Charset UTF8 = Charset.forName("UTF-8");
    Writer out = new OutputStreamWriter(new FileOutputStream("VertCover.txt"), UTF8);
    int counter = 0;
    String test = "";
    if (REDCOUNT < BLUECOUNT) {
        for (Entry<Integer, MapPoint> entry: pointMap.entrySet()) {
            if (entry.getValue().getColor() == -1) {
                test += entry.getKey().toString() + "x";
                counter++;
            }
        }
    } 
    else {
        for (Entry<Integer, MapPoint> entry: pointMap.entrySet()) {

            if (entry.getValue().getColor() == 1) {
                test += entry.getKey().toString() + "x";
                counter++;
            }
        }
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println(counter);
        out.write(test);
        System.out.println(test);

    }
    out.flush();
    out.close();
}

Current text file output: ...ㄱㅸ砲㌱㉸破㘲㉸砹ㄳ㍸砲㐳㑸砱㐴㑸砵㘴㑸砹㐵㕸砷〶㙸砱㈶㙸破㔶㙸砶㤶㝸砰ㄷ㝸砲㔷㡸砰㔸㥸砰ㄹ...

entry.getKey() is an integer: output should look like 123x4654x321x968735x168

Upvotes: 3

Views: 96

Answers (2)

kenetik
kenetik

Reputation: 350

Ok, so apaprently if your first 8 bits of your text file are hex and happen to match another random encoding code, notepad in windows changes your text files encoding. So change the first characters, or put a print line in it

Upvotes: 1

yasd
yasd

Reputation: 956

I think Notepad isn't able to handle UTF-8, but Notepad++ is, so it looks okay in Notepad++. Using Charset ISO-8859-1 instead of UTF-8 should be fine for Notepad.

Upvotes: 0

Related Questions