六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 40|回复: 0

文件读写的综合运用Reader Writer InputStream OutputStream

[复制链接]

升级  20%

2

主题

2

主题

2

主题

童生

Rank: 1

积分
10
 楼主| 发表于 2013-1-15 02:24:31 | 显示全部楼层 |阅读模式
一。基于字节的输入流

二。基于字节的输出流



三。基于字符的输入流


四。基于字符的输出流


import java.io.*;


public class ReadWriteFile {

public static void writeF(File f){
OutputStream os = null;
String str = "文件读写";
try {
os = new FileOutputStream(f);
byte[] b = str.getBytes();
os.write(b);
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("写入成功");
}

public static String readF(File f){
String str ="";
InputStream is = null;
Reader r = null;
int button = 2;
try{
switch(button){
case 1:{
System.out.println("InputStream");
is = new FileInputStream(f);
BufferedInputStream br = new BufferedInputStream(is);
byte[] b = new byte[br.available()];
br.read(b);
str = new String(b);
break;
}
case 2:{
System.out.println("Reader");
r = new FileReader(f);
BufferedReader br = new BufferedReader(r);
StringBuffer sb = new StringBuffer();
while((str = br.readLine()) != null){
sb.append(str);
}
str = new String(sb);
break;
}
}


}catch(IOException e){
e.printStackTrace();
}
return str;
}

public static void main(String[] args){
File f = new File("c:\\1.txt");
writeF(f);
System.out.println(readF(f));
}
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表