Java程序输出SOH/STX而非整数的问题求助
Hey there! Those weird SOH (Start of Header, ASCII 0x01) and STX (Start of Text, ASCII 0x02) characters you're seeing are classic signs that you're writing the raw byte value of your integer count to the file, not the human-readable string representation of that number. Let's break this down and fix it.
Why This Happens
When you write an int directly to an OutputStream (like FileOutputStream), Java writes the 4-byte binary representation of that integer. For small counts like 1 or 2:
- The value
1translates to the byte0x01— which is the SOH control character. - The value
2translates to0x02— which is STX.
Your console System.out.println(count) works because it automatically converts the integer to its string equivalent before printing. But file outputs don't do that by default.
How to Fix It
You need to convert your integer count to a string before writing it to the file. Here's a complete working version of your Q1 class that does this correctly:
import java.io.*; public class Q1 { public static void main(String[] args) { int count = 0; // Increment count each run (you might want to persist this value between runs, but this is for demo) count++; // Correct way: Write the string representation of count try (FileWriter writer = new FileWriter("output.txt", true)) { // "true" appends to the file instead of overwriting writer.write(String.valueOf(count)); writer.write(System.lineSeparator()); // Add a newline to make each count entry readable System.out.println("Count executed: " + count); } catch (IOException e) { e.printStackTrace(); } } }
Key Changes:
- Using
FileWriter(a character-based writer) instead of a byte-basedOutputStream— this handles string-to-character conversion automatically. - Wrapping
countinString.valueOf(count)to convert the integer to its human-readable string form. - Adding
System.lineSeparator()to put each count on a new line (optional but makes the file much easier to read in Notepad++).
What If You Need Byte Streams?
If you have to use FileOutputStream for some reason, convert the integer to a string first, then get its bytes:
try (FileOutputStream fos = new FileOutputStream("output.txt", true)) { String countStr = String.valueOf(count) + System.lineSeparator(); fos.write(countStr.getBytes()); } catch (IOException e) { e.printStackTrace(); }
Now when you run the program, your file will show 1, 2, 3, etc., instead of those confusing control characters.
内容的提问来源于stack exchange,提问作者Nathan Gentle

