目录
一、读入数据
流程:
1.创建需要读取的TXT文件
2.创建File类对象
3.使用File类对象去初始化FileReader对象
4.根据返回值进行遍历
方式一:逐字符读取
public static void main(String[] args) {
FileReader fr=null;
try {
File f=new File("hello.txt");
fr=new FileReader(f);
int data;当返回值为-1时,证明已经读取完数据
while (( data=fr.read())!=-1){
//System.out.println(data);
System.out.print((char)data);//将其转换为char字符输出
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fr!=null){
fr.close();//读完后应该关闭
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
方式二:使用read的重载方法,以数组的方式行读取
@Test
public void show() {
FileReader fr=null;
try {
File f=new File("D:\\Java develop\\Program\\superior_Java\\hello.txt");
fr=new FileReader(f);
char []arr=new char[5];//每次读5个
int len;//返回每一次读取的长度
while((len=fr.read(arr))!=-1){
for (int i = 0; i < len; i++) {//一定要用len,不可用arr.length,因为在数组进行取值时,是覆盖性操作
System.out.print(arr[i]);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
结果:
二、写出数据
1.提供File类的对象
2.提供FileWriter的对象
3.执行write()方法
5.关闭流资源
@Test
public void testWriter() throws IOException {
File f=new File("D:\\Java develop\\Program\\superior_Java\\hello1.txt") ;
FileWriter fw=new FileWriter(f,false);//若为TRUE,则会进行覆盖
fw.write("hello,Brandon Ingram.\n");
fw.write("I am do boring something I dont like.\n");
fw.write("I have a basketball dream.");
fw.close();//流资源关闭
}
结果:
三、读写综合例子
@Test
public void testReadWrite() throws IOException {
FileReader fr= null;
FileWriter fw= null;
try {
File f1=new File("D:\\Java develop\\Program\\superior_Java\\hello1.txt");
File f2=new File("D:\\Java develop\\Program\\superior_Java\\hello2.txt");
fr = new FileReader(f1);
fw = new FileWriter(f2);
char []arr=new char[10];
int len;
while((len=fr.read(arr))!=-1){
fw.write(arr,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fw!=null)
fr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if(fw!=null)
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
(写完后才发现文档中的语法有些许不对,不要在意!!!)