文件的读写 -- java FileInputStream

一 FileInputStream 方式读写 可以读写 jpg doc txt等文件,因为  以字节流 方式传输

二 FileReader 方式读写 只能读写txt文件,因为以 字符流 方式传输

 

package test.file;

import java.io.*;

public class FileIOTest {

 /**
  * 读取的字符 为-1 表示文件结束 对中文采用unicode
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
 
  FileIOTest f = new FileIOTest();
  try {
   f.ReadWriteFileByByte();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
 
 //用字节流传输  可以将字节流转换成指定的字符流 详见 函数ReadWriteFile
 public void ReadWriteFileByByte() throws IOException{
  
  String sfile = "c:\\企业文化(1)(1).doc";
//  String sfile = "c:\\ask.jpg";
  String dfile ="d:\\企业文化(1)(1).doc";
  File srcFile = new File(sfile);
  File destFile = new File(dfile);
  
  try {
   if(!destFile.exists()){
    destFile.createNewFile();
   }
   FileInputStream fin = new FileInputStream(srcFile);
   FileOutputStream fout = new FileOutputStream(destFile);
//   在末尾追加字符
//   FileOutputStream fout = new FileOutputStream(destFile,true);
   
//这样是不对的 因为无法检测是否为-1 表示文件结束   
//   byte[] bytes = new byte[1024];
//   fin.read(bytes);
//   fout.write(bytes);
        //  一次读取1024字节
   byte[] bytes = new byte[1024];
   while(fin.read(bytes)!=-1){
    fout.write(bytes);
    fout.flush();
   }
   
   fin.close();
   fout.close();
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
 }
 
 //用字符流输入输出  readline 一行一行地读取
 public void ReadWriteFile() throws IOException{
  //只能打开txt 文件 复制 c:\\企业文化.doc就出现乱码
  String sfile = "c:\\ProjectEstablishFinderImpl.java";
  String dfile ="d:\\ProjectEstablishFinderImpl.java";
//转换编码 这里没有用到
  File srcFile = new File(sfile);
  FileInputStream fin1 = new FileInputStream(srcFile);
  InputStreamReader ins1 = new InputStreamReader(fin1,"utf-8");
// 转换编码结束
//  File destFile = new File(dfile);
//  FileOutputStream fout = new FileOutputStream(destFile);
//  OutputStreamWriter outs = new OutputStreamWriter(fout);
  FileReader ins = new FileReader(sfile);
  FileWriter outs = new FileWriter(dfile);
  
  BufferedReader readBuf = new BufferedReader(ins);
  BufferedWriter writeBuf = new BufferedWriter(outs);
  String s = null;
  while((s=readBuf.readLine())!=null){
//   System.out.println(s);
   writeBuf.write(s);
   writeBuf.newLine();//启用新的一行
   writeBuf.flush();
  }
  readBuf.close();
  writeBuf.close();
 }

 //编码转换~~
// public String encode(byte[] array){  
//  String~~
//         return EncodingUtils.getString(array,TEXT_ENCODING);  
// } 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值