查看目錄下的所有文件,並輸出至指定文件

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;

public class Translate {

	public static void main(String[] args) {
		Translate.multiFile();
	}
 
	/**
	 * 輸出文件
	 * @param path
	 * @param content
	 */
	public static void write(String path, String content) {
		String s = new String();
		String s1 = new String();
		try {
			File f = new File(path);
			if (f.exists()) {
				System.out.println("文件存在");
			} else {
				System.out.println("文件不存在,正在創建...");
				if (f.createNewFile()) {
					System.out.println("文件創建成功!");
				} else {
					System.out.println("文件創建失敗!");
				}
			}
			// 先讀取原文件,再追加至末尾
			BufferedReader input = new BufferedReader(new FileReader(f));
			while ((s = input.readLine()) != null) {
				s1 += (s + "\n");
			}
			System.out.println("文件內容:" + s1);
			input.close();
			s1 += content;
			BufferedWriter output = new BufferedWriter(new FileWriter(f));
			output.write(s1);
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 讀取目錄下的所有文件
	 */
	public static void multiFile() {
		System.out.println("執行multiFile");
		// 讀取文件內容
		String path = "F:/veeasygenerate/src/";
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		try {
			File file = new File(path);
			File[] tempList = file.listFiles();
			System.out.println("該目錄下對象個數:" + tempList.length);
			for (int i = 0; i < tempList.length; i++) {
				if (tempList[i].isFile()) {
					// 輸出至文件,記錄相關信息
					Properties pp = System.getProperties();
					String newLine = pp.getProperty("line.separator");
					StringBuffer str_format = new StringBuffer();
					str_format.append("<filename=\"");
					str_format.append(tempList[i].getName());
					str_format.append("\"></file>");
					str_format.append(newLine);
					write("F:/veeasygenerate/result.xml", str_format.toString());
					// 
					System.out.println("文 件:" + tempList[i]);
					fos = new FileOutputStream("F:/veeasygenerate/dst/" + tempList[i].getName());
					osw = new OutputStreamWriter(fos, "GB2312");
					// read file
					if (tempList[i].exists()) {
						FileInputStream fi = new FileInputStream(tempList[i]);
						InputStreamReader isr = new InputStreamReader(fi, "utf-8");
						BufferedReader bfin = new BufferedReader(isr);
						String rLine = "";
						while ((rLine = bfin.readLine()) != null) {
							// write file
							osw.write(rLine + "\n");
							osw.flush();
						}
						bfin.close();
						isr.close();
					}
					osw.close();
					fos.close();
				}
				if (tempList[i].isDirectory()) {
					System.out.println("文件夾:" + tempList[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章