java IO 流(三)

2014-11-24 11:59:56 ? 作者: ? 浏览: 166
直接操作字符串,无需转化
Reader,FileReader其实在操作上与字节流很相似:
File f = new File("f:" + File.separator + "test.txt");
Reader is = null;
try {
is = new FileReader (f);
char b [] = new char[1024];//定义一个1024个字节的数据
try {
int len = 0;
int lend = 0;//读到的数据
while((lend = is.read()) != -1){
b[len] = (char) lend;//其实是把ASC码强力转成字符串
len++;
System.out.println(lend);
}
System.out.println("输入流的数据:" + new String(b));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Writer,FileWriter,
File f = new File("f:" + File.separator + "test.txt");
Writer os = null;
try {
os = new FileWriter (f, true);//向上转型,如果文件不存在,会自动创建,如果存在,会覆盖
String s = "I am Chinese";
try {
os.write(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {//在最后关闭,不管是否出现异常,都会执行
try {
if(os != null){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
虽然看起来很多相似的地方,但是还是有些区别:
字节流直接操作文件,字符流需要通过缓存才能操作,也就是说在字节操作中,
即使没有关闭,也会执行操作,在字符操作中,没有关闭之前,数据存在内存(缓存)中,是不会执行输出操作的
硬盘上存储的数据都是字节形式的,字符只存在于内在中.
操作实例:Copy 源文件 目标文件
String args1 [] = new String[]{
"f:" + File.separator + "test.txt",
"f:" + File.separator + "test2.txt"
};
if(args1.length!=2){ // 判断是否是两个参数
System.out.println("输入的参数不正确。") ;
System.out.println("例:java Copy 源文件路径 目标文件路径") ;
System.exit(1) ; // 系统退出
}
File f1 = new File(args1[0]) ; // 源文件的File对象
File f2 = new File(args1[1]) ; // 目标文件的File对象
if(!f1.exists()){
System.out.println("源文件不存在!") ;
System.exit(1) ;
}
InputStream input = null ; // 准备好输入流对象,读取源文件
OutputStream out = null ; // 准备好输出流对象,写入目标文件
try{
input = new FileInputStream(f1) ;
}catch(FileNotFoundException e){
e.printStackTrace() ;
}
try{
out = new FileOutputStream(f2) ;
}catch(FileNotFoundException e){
e.printStackTrace() ;
}
if(input!=null && out!=null){ // 判断输入或输出是否准备好
int temp = 0 ;
try{
while((temp=input.read())!=-1){ // 开始拷贝
out.write(temp) ; // 边读边写,最好是使用这种方式,因为如果文件过大,可能内在不够用
}
System.out.println("拷贝完成!") ;
}catch(IOException e){
e.printStackTrace() ;
System.out.println("拷贝失败!") ;
}
try{
input.close() ; // 关闭
out.close() ; // 关闭
}catch(IOException e){
e.printStackTrace() ;
}
}
四, 字节流与字符流的转换流:OutputStreamWriter,将输出的字符流转换成输出的字节流
InputStreamReader,将输入的字节流转换成输入的字符流
其实就是说字符便于在内在中操作,字节便于在硬盘中存储,在使用时进行相应的转换
OutputStreamWriter:
File f = new File("d:" + File.separator + "test.txt") ;
Writer out = null ; // 字符输出流
out = new OutputStreamWriter(new FileOutputStream(f)) ; // 字节流变为字符流
out.write("hello world
-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: