前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java写文件读写操作(IO流,字节流)

java写文件读写操作(IO流,字节流)

作者头像
用户3030674
发布2018-09-14 14:36:29
2K0
发布2018-09-14 14:36:29
举报
package copyfile;

import java.io.*;

public class copy {
	public static void main(String[] args) throws IOException {
		 copyFile("d:/new/a.txt","d:/new/b.txt",true);//oldpath,newpath,是否不覆盖前文
	}
	public static void copyFile(String oldpth,String newpath,boolean add) throws IOException{
		FileInputStream in = null;
		FileOutputStream fs = null;
		try {
			//实例化文件,并判断文件是否存在
			File oldfile=new File(oldpth);
			if(oldfile.exists()){
					//初始化文件输入与输出流
					in=new FileInputStream(oldpth);
					fs=new FileOutputStream(newpath,add);
					//定义存放读取数据的数组
					byte[] buffer=new byte[10];
					int length;
					while(true){
						int len=in.read(buffer);//当文件读完,返回-1,否则返回读取文件长度
												/*注:输出读取的当前文件内容方法
												 * String s=new String(buffer);
												 * s.trim();(去除字符串前后两端的空格)
												*/
						if(len==-1)break;
						fs.write(buffer);
					}
					System.out.println("OK");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			in.close();
			fs.close();
		}
	}
}

/** * IO流的数据写入和读取 * 在本质上是用的FileReader("c:text.txt")或FileWriter("c:text2.txt") * 通过read()或write()读取或写入单个字符存入数据中 * 由于操作起来比较麻烦效率不高。所以后来引入了缓冲流的概念, * 所以出现了BufferedReader对象,通过这个对象,将fileRead读取的数据进行缓冲 * 提高效率 * */

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-12-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档