java用io流读写_Java IO流的读写操作(掌握)

/*** 字符输出流*/

public static voidtest2() {

File file= new File("dest1.txt");

Writer fw= null;try{

fw= newFileWriter(file);

String str= "大家好,我是康纳\r哈哈";//写法 1//char[] charArray = str.toCharArray();//字符串到 字节数组//fw.write(charArray, 0, charArray.length);//写法 2//fw.write(str);//写法3

fw.append("IO is so easy\r ").append("大家好我是康纳郭");

fw.flush();

}catch(Exception e) {

e.printStackTrace();

}finally{try{if (fw != null) {

fw.close();

}

}catch(Exception e2) {

e2.printStackTrace();

}

}

}/*** 字符输入流*/

public static voidtest1() {

File file= new File("test.txt");//字符输入流

Reader fr = null;try{

fr= newFileReader(file);//操作缓冲区

char[] flush = new char[10];//每次接受字符长度

int len = -1;while ((len = fr.read(flush)) != -1) {//字符数组 到字符串

String str = new String(flush, 0, len);

System.out.print(str);

}

}catch(Exception e) {

e.printStackTrace();

}finally{try{//关流

if (fr != null) {

fr.close();

}

}catch(Exception e2) {

e2.printStackTrace();

}

}

}/*** 字符流 文件的拷贝

*

*@paramsrcPath 要复制的文件

*@paramdestPath 复制到该文件中*/

public static voidcopy(String srcPath, String destPath) {//创建源

File src = newFile(srcPath);

File dest= newFile(destPath);//创建字符流

Reader reader = null;

Writer writer= null;try{

reader= newFileReader(src);

writer= newFileWriter(dest);int len = -1;//每次读取的长度

char[] flush = new char[2];//缓冲器//int i = 0;

while ((len = reader.read(flush)) != -1) {//writer.write(i+" ");

writer.write(flush, 0, len);//writer.write("\r\n");

}

writer.flush();//刷新

} catch(Exception e) {

e.printStackTrace();

}finally{//关流

try{if (writer != null) {

writer.close();

}if (reader != null) {

reader.close();

}

}catch(Exception e2) {

e2.printStackTrace();

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值