Java 如何使用fileoutputstream写入数字
我是java新手,我需要定义计数器,然后将结果写入文件Java 如何使用fileoutputstream写入数字,java,Java,我是java新手,我需要定义计数器,然后将结果写入文件 int counter=0; int resultstweets=0; fos = new FileOutputStream(new File( prop.getProperty("PATH_TO_OUTPUT_FILE"))); BufferedReader br = new BufferedReader(new FileReader("path/of/file")); while ((tweetJson = br.readLine()
int counter=0;
int resultstweets=0;
fos = new FileOutputStream(new File(
prop.getProperty("PATH_TO_OUTPUT_FILE")));
BufferedReader br = new BufferedReader(new FileReader("path/of/file"));
while ((tweetJson = br.readLine()) != null) {
String result = drpc.execute(TOPOLOGY_NAME, tweetJson);
Status s = null;
try {
s = DataObjectFactory.createStatus(tweetJson);
result = s.getId() + "\t" + s.getText() + "\t" + result;
// this is my counter
resultstweets+=counter;
} catch (TwitterException e) {
LOG.error(e.toString());
}
fos.write(result.getBytes());
fos.write(newLine);
}
fos.write(newLine);
fos.write("Finish: ".getBytes());
fos.write("resultstweets".getBytes());
fos.write(newLine);
// here i write it in the file
fos.write(resultstweets);
但我在文件末尾得到了什么
Finish: resultstweets
**\001**459202139258
这个方法
java.io.FileOutputStream.write(byte[]b)
您在最后一行中使用的是一个字节数组作为参数
因此,您应该首先将您的整数
转换为字符串
,然后调用getBytes
:
fos.write(String.valueOf(resultstweets).getBytes());
您可以找到使用此方法的适当示例。将
文件输出流
包装在缓冲输出流
中,这样您就可以直接写入字符串
s,而无需getBytes()
任何地方。我尝试并得到类型FileOutputStream中的方法write(int)不适用于参数(字符串)@AndyTurner:他想要一个编写器,而不是输出流来编写文本数据代码>。问题中的代码已编辑。今后,请尽量只发布格式良好的代码。如果你想让这里的志愿者努力阅读和理解你的代码,那当然不是要求你付出太多努力来确保它的格式正确。这是另一个问题。。。在您的代码中,计数器初始化为零,然后从未更改。我使用初始化值定义了计数器,然后使用此行resultstweets+=counter;为了在每次从br(缓冲区读取器从文件读取)读取tweet后增加它,我可以为这个问题写另一篇文章吗!什么resultstweets+=计数器
does将0+0分配给每行的resultstweets
,这不会改变它的值,所以如果你用1初始化计数器,你可能会得到你想要的结果。非常感谢它在一周后工作,因为我的错误设置,再次感谢我将它定义为int counter=1;int resultstweets=0;