1. 程式人生 > >java 資料流讀取檔案

java 資料流讀取檔案

java檔案的讀取

檔案讀取

1)按字元編碼格式讀取

            File file = new File(path);
			if (file.isFile() && file.exists()) { // 判斷檔案是否存在
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(new FileInputStream(file), encodeName));
				String line = null;
				while ((line = reader.readLine()) != null) {
					list.add(line);
				}
				reader.close();            File file = new File(path);
			if (file.isFile() && file.exists()) {
				BufferedWriter out = new BufferedWriter(
			    new OutputStreamWriter(new FileOutputStream(file, false), encodeName));
				out.write(content);
				out.close();//追加方式寫入
				BufferedWriter out = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(file, true), "utf-8"));
				out.write(content);
				out.close(); //陣列轉換成String
 StringBuffer sb = new StringBuffer();
		for (String str : contents) {
			sb.append(str);
		}
 //list裝換成String
 String[] strArray = new String[list.size()];
 list.toArray(strArray);// list 轉換為 array
2)檔案的寫入 File file = new File(path);
if (file.isFile() && file.exists()) {
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), encodeName));
out.write(content);
out.close();
3)按字元編碼寫入  File file = new File(path);
            if (file.isFile() && file.exists()) {
                BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), encodeName));
                out.write(content);
                out.close();
4)直接覆蓋寫入  File file = new File(path);
            if (file.isFile() && file.exists()) {
                BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file, false), encodeName));
                out.write(content);
                out.close();
5)直接追加寫入  File file = new File(path);
            if (file.isFile() && file.exists()) {
                BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file, true), encodeName));
                out.write(content);
                out.close();

總結

按照一種方式讀取,直接引用這個讀取方法,之後把這個方法資料格式轉化成其他型別即可。 幾種資料型別的轉換 //陣列轉換成String
 StringBuffer sb = new StringBuffer();
        for (String str : contents) {
            sb.append(str);
        }
 //list裝換成String
 String[] strArray = new String[list.size()];
 list.toArray(strArray);// list 轉換為 array 請大家多多指教