8.文件字符流
作者:互联网
1.文件字符输入流
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();
}
}
}
}
标签:字符,txt,fw,write,printStackTrace,文件,FileWriter,null 来源: https://www.cnblogs.com/lyq888/p/16130001.html