You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序输出SOH/STX而非整数的问题求助

Fixing SOH/STX Control Characters in Your Java File Output

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 1 translates to the byte 0x01 — which is the SOH control character.
  • The value 2 translates to 0x02 — 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-based OutputStream — this handles string-to-character conversion automatically.
  • Wrapping count in String.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:26:06