简述:
在文件底部append条目(这个用在web project 中log日志输出本地持久化时有用),
此外,令有一个线程PrepareOutput用来准备主程序输出到output.txt的字符串条目
知识点:
1. 文件输出流操作
2. java线程操作(准备资源)
代码:
package test.outputFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestOutputFile {
//count is used to limit number of times to output to file output.txt
private static Integer count = 0;
//decide the authority to print something
private static boolean canPrint = false;
private static long startTime = System.currentTimeMillis();
private static long endTime;
//output string to output.txt
private static String output;
public static void main(String[] args){
File outputFile = new File("output.txt");
FileOutputStream outputFileStream = null;
// try to open file output.txt
try {
//append text at the end, NO covering the previous file
outputFileStream = new FileOutputStream(outputFile,true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
TestOutputFile testOutputFile = new TestOutputFile();
PrepareOutput prepareOutput = testOutputFile.new PrepareOutput();
Thread thread = new Thread(prepareOutput);
thread.start();
while(true){
if(canPrint){
//if printing permited,comes in then lock canPrint
//that is setting canPrint to false
canPrint = false;
try {
//append to output.txt
byte[] outputBytes = output.getBytes("UTF-8");
outputFileStream.write(outputBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
if(count == 100){
break;
}
}
//close file stream
try {
outputFileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class PrepareOutput implements Runnable{
public void run(){
while(count != 100){
endTime = System.currentTimeMillis();
if((endTime - startTime) % 10000 == 0 && !canPrint){
//prepare for output
output = "Time Now: " + System.currentTimeMillis() +
", count: " + count + "\n";
//After preparation , set canPrint to true
canPrint = true;
//one record triggers count + 1
count++;
}
}
}
}
}
输出到output.txt