Java实现文件的读写,复制

 import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream; /**
* 测试文件的读取、写入、复制功能
* @package :java05
* @author shaobn
* @Describe :测试文件的读取、写入、复制功能
* @Time: 2015-9-5 下午10:50:18
*/
public class TestCopyText {
public static void main(String[] args) throws Exception{
//读取文件并打印
System.out.println(readText(new FileInputStream("D:\\hello.txt")));
//写入内容至文件
writeText(new FileOutputStream("D:\\hellocopy.txt"), "您好,读写文件一般都用字符流,这种方式不推荐!");
//复制文件,上面写入文件内容不变
writeText(new FileOutputStream("D:\\hellocopy.txt",true),readText(new FileInputStream("D:\\hello.txt")));
}
//用FileInputStream读取文件
public static String readText(InputStream is){
BufferedInputStream bis = null;
String str = null;
try {
bis = new BufferedInputStream(is);
int len = 0;
byte[] by = new byte[1024];
while((len=bis.read(by))!=-1){
str = new String(by,0,len);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(bis!=null){
bis.close();
return str;
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
return str;
}
//用FileOutputStream写入文件
public static void writeText(OutputStream os,String str){
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(os);
bos.write(str.getBytes());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try{
if(bos!=null){
bos.close();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} } }
}

声明一下:一般读写文本文件均为字符流,笔者用字节流来写,推荐大家使用字符流读写文本文件。

上一篇:54. 八皇后问题[eight queens puzzle]


下一篇:#191 sea(动态规划)