文件的读写 -- java FileInputStream

    xiaoxiao2021-12-14  20

    一 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);   // }  }

    转载请注明原文地址: https://ju.6miu.com/read-964539.html

    最新回复(0)