首页 > 解决方案 > FileOutputStream - 二进制 I/O 和制作 int 数据 10 Java

问题描述

我有一个简单的 10 个整数的 OutputStream。我想让它成为一个有 2 行的输出。在书中,我可以在 Java 中得到 1 行 10 个整数。我想把 1 行变成 2 行 5 个整数。

1 2 3 4 5

6 7 8 9 10

我有

1 2 3 4 5

7 8 9 10

我应该怎么办?

 package chapter_17_test;

import java.io.*;

 public class TestFileStream_2 
  {
    public static void main(String[] args) throws IOException 
    {
    try (
           // Create an output stream to the file
              FileOutputStream output = new            FileOutputStream("temp_RB29.txt");  //.dat
    ) 
    {
        // Output values to the file
        for (int i = 1; i <= 10; i++)
        output.write(i);
    }

try (
        // Create an input stream for the file
        FileInputStream input = new FileInputStream("temp_RB29.txt");
    ) 
    {
        // Read values from the file
        int test = 1;
        int value;
        while ((value = input.read()) != -1 && test < 11)
        {   
            if ((test % 6) != 0)
            System.out.print(test + " ");
            else
                System.out.println("\n");
            test++;
        }
    }
        System.out.println("");
 }
}

标签: for-loopinputbinary

解决方案


这里:

            if ((test % 6) != 0)
            System.out.print(test + " ");
            else
                System.out.println("\n");

,请注意,在一种情况下您打印test + " ",而在另一种情况下您只打印"\n",没有test. 这就是为什么 6 从您的输出中省略的原因。另请注意,您的输出分布在三行(一行空白),而不是两行。

既然你总是想打印test,那么无条件打印会更干净。只有分隔符需要有条件地打印。例如,

            System.out.print(test);
            if ((test % 5) != 0)
                System.out.print(' ');
            else
                System.out.println();

推荐阅读