/**
* 監控控制檯,每當控制檯輸入一行數據時就往磁盤裏面寫,磁盤有文件專門存放,
* 文件內容長度不能超過50個字符,超過時自動建立新文件並把超過的內容放到新文件中去
* (要求程序關閉後再啓動輸入數據不會覆蓋原來的數據)。
* 問題:①數據長度超過50,就自動建立新的文件,將多餘的數據寫入,
* 且寫入的數據不得超過50,若超過又重新創建,以此循環。
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 監控控制檯,每當控制檯輸入一行數據時就往磁盤裏面寫,磁盤有文件專門存放,
* 文件內容長度不能超過50個字符,超過時自動建立新文件並把超過的內容放到新文件中去
* (要求程序關閉後再啓動輸入數據不會覆蓋原來的數據)。
* 問題:①數據長度超過50,就自動建立新的文件,將多餘的數據寫入,
* 且寫入的數據部得超過50,若超過又重新創建,以此循環。
*
* @author 小苗
*/
public class CopyOfWriteFile002 {
private BufferedReader in_br;
private RandomAccessFile out_r;
private File file = new File("d:\\20100514zuoye.txt");
{ //初始化 輸出流
in_br = new BufferedReader(new InputStreamReader(System.in));
try {
out_r = new RandomAccessFile(file, "rw");
out_r.seek(out_r.length()); // 設置從該文件末尾開始寫入
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//讀取控制檯數據
public void read() {
System.out.println("請輸入數據:");
String str = null;
try {
while ((str = in_br.readLine()) != null) {
splitFile(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out_r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//拆分數據循環創建50字節大小的文件
public void splitFile(String str) throws IOException{
byte[] byte2 = str.getBytes(); // 解決亂碼問題
long len = str.length();
/* 如果輸入的數據與目標文件的大小和大於50,且目標文件大小大於50 就創建新文件
* 若目標文件大小小於50,就寫入50-out_r.length()長度的數據
*/
if (len+out_r.length() >=50) {
if(out_r.length()>=50){
createFile(file); //創建文件方法
splitFile(str);
}else{
long buff = 50-out_r.length();
out_r.seek(out_r.length());
out_r.write(byte2,0,(int)buff);
if((len-buff)>0){
str = str.substring((int)buff);
splitFile(str); //用遞歸
}
}
}else{
out_r.write(byte2);
return;
}
}
// 創建新文件以當前時間命名,重新賦值輸出流
public void createFile(File file) throws IOException {
Date date = new Date(); // 獲取當前時間
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // 定義文件名格式
String formatDate = sdf.format(date); // 把當前時間以定義的格式 格式化
String str1 = file.getParent() + "\\";
String str2 = str1.concat(formatDate);
String nameDate = str2 + ".txt"; // 定義路徑
out_r = new RandomAccessFile(nameDate, "rw"); // 獲得寫入目標文件
}
public static void main(String[] args) throws ParseException, IOException {
CopyOfWriteFile002 wf = new CopyOfWriteFile002();
wf.read();
}
}