溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java如何實現(xiàn)文件簡單讀寫

發(fā)布時間:2022-03-21 14:52:51 來源:億速云 閱讀:136 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了java如何實現(xiàn)文件簡單讀寫,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

文件簡單讀寫

package com.file;

import java.io.*;

/**
 * Created by elijahliu on 2017/2/11.
 */
public class ReadFile {
  public static void main(String[] args) {
    File file = new File("new Hello.txt");
    if(file.exists()){
      System.err.print("exsit");
      try (FileInputStream fis = new FileInputStream(file)) {//文件輸入流 這是字節(jié)流

        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//inputstreamReader是一個字節(jié)流,將字節(jié)流和字符流轉(zhuǎn)化的時候,就需要制定一個編碼方式,不然就會亂碼
        BufferedReader br = new BufferedReader(isr);//字符緩沖區(qū)

        String line;
        while((line = br.readLine())!=null){//這里將緩沖區(qū)里的內(nèi)容如果非空就讀出來打印
          System.out.println(line);

        }
        br.close();//最后將各個線程關(guān)閉
        isr.close();
        fis.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    File newfile = new File("newtext.txt");
    try {
      FileOutputStream fos = new FileOutputStream(newfile);//這里如果文件不存在會自動創(chuàng)建文件
      OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");//和讀取一樣這里是轉(zhuǎn)化的是字節(jié)和字符流
      BufferedWriter bw = new BufferedWriter(osw);//這里是寫入緩沖區(qū)

      bw.write("厲害了我的哥");//寫入字符串

      bw.close();//和上面一樣 這里后打開的先關(guān)閉 先打開的后關(guān)閉
      osw.close();
      fos.close();
      System.out.println("done");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“java如何實現(xiàn)文件簡單讀寫”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI