8.檔案字元流
阿新 • • 發佈:2022-04-11
import java.io.FileReader;
public class Dome05 {
public static void main(String[] args) {
FileReader frd = null;
try {
//建立檔案字元流輸入物件
frd = new FileReader("d:/a.txt");
int temp = 0;
while ((temp = frd.read()) != -1) {
System.out.println((char)temp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (frd != null) {
frd.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2.檔案字元輸出流
D盤下沒有b.txt檔案,會自動建立這個檔案
import java.io.FileWriter;
public class Dome06 {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("d:/b.txt");
fw.write("你好");
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
當我們使用多次 fw.write() ,預設會對內容進行追加
import java.io.FileWriter;
public class Dome06 {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("d:/b.txt");
fw.write("你好");
fw.write("世界");
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
同樣用 FileReader 物件對同一個檔案進行操作,預設內容將進行覆蓋(\r\n表示回車換行),如需要追加,則需要在後面加true 【new FileWriter("d:/b.txt",true)】
import java.io.FileWriter;
public class Dome06 {
public static void main(String[] args) {
FileWriter fw1 = null;
FileWriter fw2 = null;
try {
fw1 = new FileWriter("d:/b.txt");
fw2 = new FileWriter("d:/b.txt");
fw1.write("你好");
fw1.write("世界");
fw1.flush();
fw2 = new FileWriter("d:/b.txt");
fw2.write("你好\r\n");
fw2.write("世界");
fw2.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fw1 != null) {
fw1.close();
}
if (fw2 != null) {
fw2.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}