Java 当中的IO(二)-- MarsChen Java4Android 教程学习笔记

大文件的读写方法
每次输入Buffer 1k 字节的数据,从Buffer 输出1k 字节,一直重复到全部数据传输完毕。
   
   
import java.io.*;
public class test{
public static void main(String args[] ){
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream("e:/Java4Android/from.txt");
fos=new FileOutputStream("e:/Java4Android/to.txt");
byte [] buffer=new byte[1024];
while(true){
int temp=fis.read(buffer,0,buffer.length);
if(temp==-1){
break;
}
fos.write(buffer,0,temp);
}
}catch(IOException ex){
System.out.println(ex);
}
finally{
try{
fis.close();
fos.close();
}catch(Exception e){
System.out.println(e);
}
}
}
}


字符流的使用方法
字符流即读写文件时以字符为基础。注意,buffter 是char 类型的。操作方法和字节流非常类似。
核心类:输入流都是Reader 类的子类,常用FileReader。输出流都是Writer 类的子类,常用FileWriter。
核心方法:
输入流:
int read(char[] c, int off, int len);
输出流:
void write(char[] c, int off, int len);
   
   
import java.io.*;

public class testChar{
public static void main(String arg[]){
FileReader fr=null;
FileWriter fw=null;
try{
fr=new FileReader("e:/Java4Android/from.txt");
fw=new FileWriter("e:/Java4Android/to.txt");
char buffer[]=new char[100];
int temp= fr.read(buffer,0,buffer.length);
fw.write(buffer,0,temp);
}catch(IOException e){
System.out.println(e);
}finally{
try{
fr.close();
fw.close();
}catch(Exception ev){
System.out.println(ev);
}
}
}
}

字符流大字节的传输方法:

import java.io.*;

public class iochar{
public static void main(String arg[]){
FileReader fr=null;
FileWriter fw=null;
try{
fr= new FileReader("e:/Java4Android/from.txt");
fw= new FileWriter("e:/Java4Android/to.txt");
char buffer[] =new char[100];
while(true){
int temp=fr.read(buffer,0,buffer.length);
if(temp==-1){
break;
}
fw.write(buffer,0,temp);
}
}catch(Exception e){
System.out.println(e);
}finally{
try{
fr.close();
fw.close();
}catch(Exception ev){
System.out.println(ev);
}
}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值