Java 实现文件的输入输出流:用 FileWriter写入字符并用FileReader读出字符
程序员文章站
2022-03-14 15:55:26
...
package com.ggx.exercise;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class testWriter {
public static void main(String[] args) {
test_wiiter();//写入字符;
test_reader();//读出字符;
}
public static void test_wiiter() {
// mainxinag面向字符流
FileWriter filewriter = null;
//FileWriter 继承自 OutputStreamWriter ,其构造方法基本一致;
try {
filewriter = new FileWriter("e:\\in.txt");
filewriter.write("jxbjkcxjvhx");// 写入内容
filewriter.write('中');
filewriter.write("我手机号是123456", 3, 3);
filewriter.flush();// 刷新缓冲区
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (filewriter != null)
filewriter.close(); //关闭流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void test_reader() {
FileReader filereader = null;
try {
filereader = new FileReader("e:\\in.txt");
char[] data = new char[1024];
try {
int len = filereader.read(data);
System.out.println(len);
System.out.println("第一种输出文件方法:");
System.out.println(data);
System.out.println("第二种输出文件方法:");
filereader = new FileReader("e:\\in.txt");// 因为上面那已经读到了文件末尾,此时需要重读文件,否则输出全部是-1
for (int i = 0; i < len; i++)
System.out.print((char) filereader.read());// 必须强制类型转换,不然输出的都是ASCII码;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (filereader != null)
filereader.close();//关闭流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
上一篇: 算法笔记 — 又一版 A+B
下一篇: 第五课--转换