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