負責維護某系統寫的
主要是爲了將一個文件目錄下的所有TXT文件都寫到同一個文件中,還對不同行之間保留了換行。參看writeALL
這個類還包括了刪除一個目錄下所有的文件,由於我確定目錄下不會有文件夾因此,沒有寫是否爲目錄的判斷操作
感覺寫的不算太好,囉囉嗦嗦的,隨意看吧
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
public class TXTHandle {
String folderpath;//文件路徑獲取
String TXTpath;//保存的TXT路徑+名稱
public TXTHandle(String FileNameStr) {
File temp = new File(FileNameStr);
this.folderpath=temp.getName();
this.folderpath=FileNameStr.replace(folderpath, "");
this.TXTpath=FileNameStr.replace("XX.xls", "All.txt");
}
//本類是負責對輸出ALLText文件以及刪除所有目前存在的txt文件而存在的
public boolean writeAll() {
System.out.println(this.folderpath);
File dir = new File(this.folderpath);
File[] files = dir.listFiles();// 該文件目錄下文件全部放入數組
File all=new File(this.TXTpath);
//文件不存在則創建,注意已存在文件就會繼續在之前的文件上繡
if(!all.exists())
{
try {
all.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//追加的方式,創建輸出流
FileOutputStream fs=null;
try {
fs = new FileOutputStream(all, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fs);
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()&& files[i].getAbsolutePath().endsWith(".txt")){
System.out.println(files[i].isFile() + " " + files[i].getAbsolutePath());
String str="";
try {
str = readFileContent(files[i]);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//bufferedOutputStream.write(hexStr2Byte(codeStr));
bufferedOutputStream.write(str.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
bufferedOutputStream.close();
fs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
public static String readFileContent(File file) throws IOException{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
while(br.ready()){
sb.append(br.readLine());
sb.append("\r\n");
}
br.close();
// sb.append("\r\n");
// System.out.println(sb.toString());
return sb.toString();
}
public boolean deleteALLTXT(){
//注意本方法是刪除所有目前存在的TXT文件,以防多次寫入
File file = new File(this.folderpath);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()&& files[i].getAbsolutePath().endsWith(".txt")){
files[i].delete();
}
}
return true;
}
return false;
}
}