Java 在文件底部新增条目,另有线程准备资源(技术原型)

简述:

在文件底部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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值