我正在开发一个人工智能项目,我应该在 NXT 上使用模糊逻辑实现一个 Controller 。为了正确评估我的控制策略,我需要跟踪颜色传感器测量的信息以及发送到电机的数据。为此,我试图实现一个简单的代码来将一些类似的信息写入 .txt 文件。这是我迄今为止所完成的工作:
import java.io.*;
import lejos.nxt.*;
public class DataLogger {
public static void main(String[] args) {
int count = 0;
FileOutputStream fileStream = null;
try {
fileStream = new FileOutputStream(new File("Test.txt"));
} catch (Exception e) {
LCD.drawString("Can't make a file", 0, 0);
System.exit(1);
}
DataOutputStream dataStream = new DataOutputStream(fileStream);
do {
try {
dataStream.writeChars(String.valueOf(count));
fileStream.flush();
count++;
} catch (IOException e) {
LCD.drawString("Can't write to the file", 0, 1);
System.exit(1);
}
} while (count < 100);
try {
fileStream.close();
} catch (IOException e) {
LCD.drawString("Can't save the file", 0, 1);
System.exit(1);
}
}
}
通过这段代码,我基本上尝试将 0 到 99 之间的数字写入名为 Test.txt 的文件中。我不知道为什么,但程序正在写入这样的数据:
0 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 ...
如您所见,它在每个数字之间添加空格。我已经尝试过许多 DataOutputStream 的写入方法,而 dataStream.writeChars(String.valueOf(count));
是“最成功”的一种(其他方法如 writeInt(int b)
根据 ASCII 表写入数据)。我也尝试过使用 BufferedOutputStream 类,但没有成功。我可能做错了什么?
最佳答案
您使用了错误的方法将基本文本数据写入文件。来自Java 7 API文档:
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.
此外,最佳做法是使用 try-with-resources而不是手动关闭文件。
这是我测试过的测试类的更新版本:
import java.io.*;
public class DataLogger {
public static void main(String[] args) {
int count = 0;
String filename = "Test.txt";
File file = new File(filename);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
if ( ! file.exists() ) {
file.createNewFile();
}
do {
writer.write(Integer.toString(count));
count++;
} while (count < 100);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
请记住,必须首先将整数转换为字符串,否则它将被视为字符引用。
此外,System.out.println()
可以与 EV3 一起使用,作为 LCD.drawString()
的替代方案,用于在 LCD 屏幕上的下一个可用行上写入时(通过滚动)记录错误,并将输出保存到 EV3 上的文件中以进行调试。
关于java - 乐约斯 : How write integer data succesfully to a file in NXT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31094329/