[英]How can I make DataOutputStream write a bool or integer to a txt file?
public static void outputFile() {
HabitItem it;
try {
File path = new File("output.txt");
FileOutputStream fout = new FileOutputStream(path);
DataOutputStream dos = new DataOutputStream(fout);
while (!stackHabitItems.isEmpty()) {
it = stackHabitItems.pop();
dos.writeChars("<\n");
for(int i = 0; i < 7; i++) {
if (it.isDayCompleted[i]) {
dos.writeInt(1);
}
else {
dos.writeInt(0);
}
}
dos.writeChars("\n");
dos.writeInt(it.id);
dos.writeChars("\\>\n");
}
fout.close();
}
catch (Exception e) {
System.out.println("Failed to open file output.txt");
}
}
All I'm trying to do is write an array of booleans and an integer into a file enclosed by < /> 我要做的就是将布尔数组和整数写入到</>包围的文件中
My file might look like this (assuming one iteration) < 1 0 1 0 0 0 1 42 > 我的文件可能看起来像这样(假设有一个迭代)<1 0 1 0 0 0 1 42>
But the dos.writeInt is failing to produce normal output. 但是dos.writeInt无法产生正常的输出。 Instead it displays <
而是显示<
? ? > Where the blank spaces are filled by Squares
> 空格由正方形填充的地方
Why does my code not work? 为什么我的代码不起作用? I feel like I'm using DataOutputStream correctly.
我觉得我在正确使用DataOutputStream。
Try PrintStream
or your FileOutputStream
directly instead and it will produce human readable results. 直接尝试使用
PrintStream
或FileOutputStream
,它将产生易于阅读的结果。
You could try like this (might still need separators between int
s) 您可以尝试这样(可能仍需要
int
之间的分隔符)
public static void outputFile() {
File path = new File("output.txt");
try (FileOutputStream fout = new FileOutputStream(path);
PrintWriter dos = new PrintWriter(fout)) {
while (!stackHabitItems.isEmpty()) {
HabitItemit = stackHabitItems.pop();
dos.println("<");
for(int i = 0; i < 7; i++) {
if (it.isDayCompleted[i]) {
dos.print(1);
}
else {
dos.print(0);
}
}
dos.println();
dos.print(it.id);
dos.println("\\>");
}
} catch (Exception e) {
System.out.println("Failed to open file output.txt");
}
}
How can I make
DataOutputStream
write a bool or integer to txt file?如何使
DataOutputStream
将布尔或整数写入txt文件?
You can't. 你不能 Booleans and integers are primitive data types.
布尔值和整数是原始数据类型。 You can either write them as binary with
DataOutputStream
to a binary file, or write them as Strings
to a text file with a Writer
and constructions such as writer.write(""+bool)
. 您可以把它们写为二进制
DataOutputStream
二进制文件, 或将它们写成Strings
文本文件与Writer
和结构,如writer.write(""+bool)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.