专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java的IO流读写文件需要注意的几点

Java的IO流读写文件需要注意的几点

更新时间:2020-08-24 16:55:32 来源:动力节点 浏览1628次

平时写IO相关代码机会挺少的,但却都知道使用BufferedXXXX来读写效率高,没想到里面还有这么多陷阱,这两天突然被其中一个陷阱折腾一下:读一个文件,然后写到另外一个文件,前后两个文件居然不一样?

解决这个问题之后,总结了几个注意点。

public void copyFile1() {
		File srcFile = new File("E://atest//atest.txt");
		File dstFile = new File("E://btest//btest.txt");
		BufferedReader in = null;
		BufferedWriter out = null;
		try {
			in = new BufferedReader(new FileReader(srcFile));
			out = new BufferedWriter(new FileWriter(dstFile));
			
			String line = null;
			while((line = in.readLine()) != null) {
				out.write(line+"/r/n");
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			if(in != null) {
				try {
					in.close();
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			
			if(out != null) {
				try {
					out.close();
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}

上面代码使用BufferedReader一行一行地读取一个文件,然后使用BufferedWriter把读取到的数据写到另外一个文件中。如果文件是ASCCII形式的,则内容还是能够正确读取的。但如果文件是二进制的,则读写后的文件与读写前是有很大区别的。当然,把上面的readLine()换成read(char[])仍然不能正确读写二进制文件的。读写二进制文件请接着看下面注意点。

注意点二:read(byte[]b,int offset,int length)中的offset不是指全文件的全文,而是字节数组b的偏移量

现在已经知道使用Reader/Writer不能正确读取二进制文件,这是因为Reader/Writer是字符流,那就改用字节流ufferedInputStream/BufferedOutputStream,网上搜索到的例子大概是这样的:

public void copyFile() {
		File srcFile = new File("E://atest//atest.gif");
		File dstFile = new File("E://atest//btest.gif");
		BufferedInputStream in = null;
		BufferedOutputStream out = null;		
		try {
			in = new BufferedInputStream(new FileInputStream(srcFile));
			out = new BufferedOutputStream(new FileOutputStream(dstFile));
			
			byte[] b = new byte[1024];
			while(in.read(b) != -1) {
				out.write(b);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			if(in != null) {
				try {
					in.close();
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			if(out != null) {
				try {
					out.close();
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}
	}

每次读1024字节,然后写1024字节。这看似挺正确的,但实际写出来的文件与原文件是不同的。这样就怀疑可能是读写没有接上,因而把代码改成下面的形式:

byte[] b = new byte[1024];
			int offset = 0;
			int length = -1;
			while((length = in.read(b, offset, 1024)) != -1) {
				out.write(b, offset, length);
				offset += length;
			}

这是误以为:先读一段,写一段,然后改变偏移量,然后使用新的偏移量再读一段、写一段,直到文件读写完毕。但这是错误的,因为使用BufferedXXX后,里面已经实现了这个过程。而read(byte[] b, int offset, int length)中的offset实际指的是把读到的数据存入到数组b时,从数组的哪个位置(即offset)开始放置数据;同理,write(byte[] b, int offset, int length)就是把b中的数据,从哪个位置(offset)开始写到文件中。

java的io流读写文件

以上就是动力节点java培训机构的小编针对“Java的IO流读写文件需要注意的几点”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>