天天看點

java 讀檔案,寫檔案,複制檔案(使用檔案輸入輸出流)

1.勿使用:

  • 讀檔案:
BufferedReader bf=new BufferedReader(new FileReader(File))
           

因為隻能将資料讀取到字元數組中

public int read(char cbuf[]) throws IOException {
    return read(cbuf, 0, cbuf.length);
}
           
  • 寫檔案:
PrintWriter pw=new PrintWriter(fileName);
           

因為隻能寫字元數組

public void write(char buf[], int off, int len) {
    try {
        synchronized (lock) {
            ensureOpen();
            out.write(buf, off, len);
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}
           

因為讀取的檔案中可能出現特殊編碼的字元,不屬于可列印字元就會導緻讀取錯誤。

2.建議使用檔案流讀寫檔案:

try{
        FileInputStream  fis=new FileInputStream(readFile);
        FileOutputStream fos=new FileOutputStream(writeFile);
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    byte[] byteArray = new byte[1024];
    int byteLength= 0;
        try{
        while ((byteLength = fis.read(byteArray)) != -1) {
            fos.write(byteArray,0,byteLength);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        fis.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
           

3.檔案複制:

try{
        FileInputStream  fis=new FileInputStream(readFile);
        FileOutputStream fos=new FileOutputStream(writeFile);
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    }
try{
    Files.copy(fis, fos, StandardCopyOption.REPLACE_EXISTING)
   }catch (Exception ex) {
      ex.printStackTrace();
   }
try{
        fis.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }