我的java代碼接收像twitter這樣的流數據。我需要存儲數據,例如每個文件10000條記錄。所以,我需要重新創建file writer
和buffered writer
以創建一個新文件,然後在其上寫入數據。java.io.IOException:流關閉。將流數據寫入多個文件的最佳方式是什麼?
// global variables
String stat;
long counter = 0;
boolean first = true;
Date date;
SimpleDateFormat format;
String currentTime;
String fileName;
BufferedWriter bw = null;
FileWriter fw = null;
public static void main(String[] args) {
String dirToSave = args[0];
String fileIdentifier = args[1];
createFile(dirToSave, fileIdentifier);
StatusListener listener = new StatusListener() {
@Override
public void onStatus(Status status) {
stat = TwitterObjectFactory.getRawJSON(status);
try {
if(bw!=null){
bw.write(stat + "\n");
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
counter++;
if (counter == 10000) {
createFile(dirToSave, fileIdentifier);
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
counter = 0;
}
}
};
TwitterStream twitterStream = new TwitterStreamFactory(confBuild.build()).getInstance();
twitterStream.addListener(listener);
// twitterStream.filter(filQuery);
}
public static void createFile(String path, String fileIdentifier) {
date = new Date();
format = new SimpleDateFormat("yyyyMMddHHmm");
currentTime = format.format(date);
fileName = path + "/" + fileIdentifier + currentTime + ".json";
// if there was buffer before, flush & close it first before creating new file
if (!first) {
try {
bw.flush();
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(LocalFile_All_en.class
.getName()).log(Level.SEVERE, null, ex);
}
} else {
first = false;
}
// create a new file
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
} catch (IOException ex) {
Logger.getLogger(Stack.class
.getName()).log(Level.SEVERE, null, ex);
}
}
但是,我總是在幾個小時後出錯。
SEVERE: null
java.io.IOException: Stream closed
編輯:該錯誤消息說,這些代碼拋出錯誤
if (counter == 10000) {
createFile(dirToSave, fileIdentifier);
...
和
bw.flush();
什麼是我的代碼的問題嗎?還是有更好的方式來寫這樣的流數據?
它是一個多線程程序嗎? – Alex
@Alex不,它只有一個線程。接收流數據並存儲到文件。 –
如何調用'onStatus'方法?哪一行引發異常? – Alex