Java中关于文件读写

               字节流              字符流

输入       InputStream     Reader

输出       OutputStream  Writer

字节流的文件包括图片,音乐等,字符流文件主要是文本文件

字节流文件输入输出

//		File f = new File("d:\\input.txt");    
//		File out = new File("d:\\output.txt");
		//也可以是图片文件
		File f = new File("d:\\IMG_1526.JPG");    
		File out = new File("e:\\IMG_1526.JPG");
		
		FileInputStream is = null;
		FileOutputStream os=null;
		// System.out.println(f.getAbsolutePath());

		try {
			os = new FileOutputStream(out);
			is = new FileInputStream(f);
			byte[] bytes = new byte[512];
			int n = 0;
			while ((n = is.read(bytes)) != -1) {
				//String s = new String(bytes, 0, n);
				//System.out.println(s);
				//os.write(s.getbytes());
				os.write(bytes);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

字符流文件输入输出

File f = new File("d:\\input.txt");    
		File out = new File("d:\\output.txt");
		FileReader is = null;
		FileWriter os=null;
		// System.out.println(f.getAbsolutePath());

		try {
			os = new FileWriter(out);
			is = new FileReader(f);
			char []a = new char[1024];
			int n = 0;
			while ((n = is.read(a)) != -1) {
				//String s = new String(bytes, 0, n);
				//System.out.println(s);
				//os.write(s.getbytes());
				os.write(a,0,n);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

缓冲字符流主要针对string,可以一行一行的进行读取

BufferReader       BufferWriter

File f = new File("d:\\input.txt");    
		File out = new File("d:\\output.txt");
		FileReader is = null;
		FileWriter os=null;
		BufferedReader br=null;
		BufferedWriter bw=null;
		// System.out.println(f.getAbsolutePath());

		try {
			os = new FileWriter(out);
			is = new FileReader(f);
			br = new BufferedReader(is);
			bw = new BufferedWriter(os);
			String str="";
			while ((str = br.readLine()) != null) {
				//String s = new String(bytes, 0, n);
				//System.out.println(s);
				//os.write(s.getbytes());
				bw.write(str+"\r\n");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				br.close();
				bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值