java – why is the output from text file like a square symbol?

java – why is the output from text file like a square symbol?
here’s the code:

import java.io.*;
import java.util.*;
public class readtext2 {
public static void main(String[] args) throws IOException {
Scanner s = null;
int sum = 0;
FileOutputStream out = null;
FileInputStream in = null;
try {
out = new FileOutputStream(“output.txt”);

s = new Scanner(new BufferedReader(new FileReader(“C:\input.txt”)));
s.useLocale(Locale.US);

while (s.hasNext()) {
if (s.hasNextInt()) {
sum += s.nextInt();
} else {
s.next();
}
}

out.write(sum);

} finally {
s.close();
}

// System.out.println(sum);

}
}

the output of this program goes in a notepad and i always get the [ ] output…but in the console the output is perfectly fine…
how come?

Best answer:

walk in toilet
see this
wat do

Tags: , , , , , , ,

Under Forum

2 Comments for java – why is the output from text file like a square symbol?

  • 1. M. L.  |  March 2nd, 2007 at 11:08 am

    Because write() and println() are not the same.

    You are taking in a bunch of characters as ints… adding them together to create a large int (why?) then writing it back out (again, why?).

    System.out.println() will convert the large int into a String. That is, if sum is 1234, it will be converted into the text “1234″.

    However, FileOutputStream.write(int) writes it out as bytes. That is, if sum is 1234, it will write out the Unicode value of 1234, which is gibberish (actually, its “CYRILLIC CAPITAL LETTER A WITH DIAERESIS”, which you probably can’t render with your font). If attempted to be read as ASCII, it’ll be multiple characters of gibberish.

  • 2. Mark aka jack573  |  March 2nd, 2007 at 11:52 am

    As M. L. saidm you are using the method write to write to the file. It only writes bytes. If you want to use a print or println method, so it can be readable, you need to use a PrintStream.

    So, you could try this piece of code:

    FileOutputStream out = null;
    PrintStream outToFile = null; // Change the name to whatever you want.
    FileInputStream in = null;
    try {
    out = new FileOutputStream(“output.txt”);
    outToFile = new PrintStream(out, true);

    instead of

    FileOutputStream out = null;
    FileInputStream in = null;
    try {
    out = new FileOutputStream(“output.txt”);

    Then use

    outToFile.print(sum);

    or

    outToFile.println(sum);

    instead of

    out.write(sum);

    The Java API on PrintStream is here:
    java.sun.com/javase/6/docs/api/java/io/PrintStream.html

Leave a Comment for java – why is the output from text file like a square symbol?

You must be logged in to post a comment.

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories