今天搞了下java文件的读写,自己也总结了一下,但是不全,只有两种方式,先直接看代码:

public static void main(String[] args) throws IOException {
io();
buffer();
} /**
* 以流的形式读写 可以使用任何文件 特别是二进制文件
*
* @author hh
* @date 2014-12-11
* @throws IOException
*/
public static void io() throws IOException {
String fname = "C:/Users/Administrator/Desktop/T.jar";
String fname2 = "C:/Users/Administrator/Desktop/T2.rar";
File file = new File(fname);
File file2 = new File(fname2);
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(file2);
byte[] bytes= new byte[2048];
int k = 0;
while((k=in.read(bytes))!=-1){
out.write(bytes);
/*for (int i = 0; i < bytes.length; i++) {//这样效率很低
out.write(bytes[i]);
}*/
}
/*或者
* int b = 0 ;
while((b=in.read())!=-1) {
out .write(b);
} */
out.close();
in.close();
System.out.println("end");
} /**
* 以字符的形式读写 实用文文本文件
* 不适用与压缩等二进制文件 否者写出来的文件会比源文件大
* @author hh
* @date 2014-12-11
* @throws IOException
*/
public static void buffer() throws IOException {
String fname = "C:/Users/Administrator/Desktop/1234.txt";
String fname2 = "C:/Users/Administrator/Desktop/kk.txt";
File file = new File(fname);
InputStreamReader read = new InputStreamReader(new FileInputStream(file),"GBK");//解决中文乱码
//FileReader read = new FileReader(file); 也可以直接使用FileReader 但是会出想中文乱码
FileWriter fw = new FileWriter(fname2);
BufferedReader bufferedReader = new BufferedReader(read);
BufferedWriter b = new BufferedWriter(fw);
String s =null;
while ((s = bufferedReader.readLine()) !=null) {
System.out.println(s);
b.write(s);
b.newLine();//换行
b.flush(); }
b.close();
read.close();
fw.close();
System.out.println("---end");
}

第一种使用的是FileInputStream和FileOutputStream,这种方式是直接使用io流读数据。不管什么文件可以搞定。但是缺点是没读一次就要进行一次io操作,若是文件大了,销量很低。

第二种使用BufferedReader 和BufferedWrite。与前面的区别是使用了缓存,读取的是字符(FileInputStream是字节)。所以之前在使用BufferedReader 和BufferedWrite复制一个压缩文件时,复制后的文件总是原文件大小的2倍。

最新文章

  1. Web缓存杂谈
  2. MYSQL之基本操作
  3. MySQL Cluster 集群简介
  4. 【7集iCore3基础视频】7-7 Qt5.2.1安装
  5. oracle的加密和解密
  6. 深入理解CSS线性渐变linear-gradient
  7. EasyUI treegrid 获取编辑状态中某字段的值 [getEditor方法获取不到editor]
  8. php正则表达式、数组
  9. node js 调试
  10. SSH配置动态数据源
  11. struts2与struts1整合,Unable to load configuration. - interceptor-ref ... struts.xml
  12. Spark RDD概念学习系列之RDD的5大特点(五)
  13. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-007-定义切面的around advice
  14. [Android] An internal error occurred during: &quot;Launching New_configuration&quot;. Path for project must have only one segment.
  15. Windows Thrift安装及HelloWorld
  16. 【稳定婚姻问题】【HDU1435】【Stable Match】
  17. CSV 客座文章系列:KGroup 通过 Windows Azure 将 Qoob 内容管理发布到云中
  18. 利用node,跑项目。
  19. java.sql.SQLException: ORA-00932: 数据类型不一致: 应为 -, 但却获得 CLOB
  20. hbase的写和读,大合并和小合并

热门文章

  1. canvas ---1
  2. 最近公共祖先:LCA及其用倍增实现 +POJ1986
  3. 在git bush中如何退出vim编辑器
  4. MySQL STRAIGHT_JOIN
  5. dedecms 织梦ping服务插件 最新破解可用版
  6. 如何监听input的脚本赋值
  7. IOS 解析XML文档
  8. C#进程间通信--API传递参数(SendMessage)
  9. python 执行shell命令
  10. iptables 顺序