for-loop - 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("");
}
}
解决方案
这里:
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();
推荐阅读
- docker - Kubernetes - 从 Minikube 到生产
- javascript - 根据切片后数组中剩余的内容显示数组的长度
- cryptography - 有效地生成不同的随机数
- python - matplotlib 删除绘图和 y 轴之间的空格
- html - 如何使带有按钮的图像具有响应性
- flutter - 在 Flutter 中使用 StaggeredGridView 时,有没有办法优化布局以最小化空白?
- postgresql - Idea 在使用 Postgresql 语言注入的字符串中找不到我的表
- r - R data.table:根据名称存储在其他地方的变量选择行
- c++ - Windows 服务不捕获关闭事件 C/C++
- list - 试图填写班级列表