java 資料流讀取檔案
阿新 • • 發佈:2019-01-30
java檔案的讀取
檔案讀取
1)按字元編碼格式讀取
2)檔案的寫入 File file = new File(path);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
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();
總結
StringBuffer sb = new StringBuffer();
for (String str : contents) {
sb.append(str);
}
//list裝換成String
String[] strArray = new String[list.size()];
list.toArray(strArray);// list 轉換為 array 請大家多多指教