溫馨提示×

溫馨提示×

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

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

Java中怎么實(shí)現(xiàn)文件讀取和寫入

發(fā)布時(shí)間:2021-08-06 17:15:09 來源:億速云 閱讀:165 作者:Leah 欄目:編程語言

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)Java中怎么實(shí)現(xiàn)文件讀取和寫入,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

需求說明

實(shí)際操作過程中,從D盤根目錄下的ak.txt讀取文件寫入D盤根目錄下的hello.txt文件內(nèi)

實(shí)現(xiàn)思路

寫兩個(gè)方法,一個(gè)用于讀取目標(biāo)文件,一個(gè)用于寫入目標(biāo)文件--詳情見代碼注釋

代碼內(nèi)容

文件讀取和寫入練習(xí)

package com.io;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * @auther::9527 * @Description: 嘗試 * @program: shi_yong * @create: 2019-07-31 17:11 */public class Tyy {  public static void main(String[] args) {    //實(shí)例化對象   Tyy tyy = new Tyy();   //用一個(gè)byte[]接受數(shù)據(jù)   byte[] bytes=tyy.read("d:/ak.txt");   //將接受到的數(shù)據(jù)傳入寫入方法   tyy.write("d:/hello.txt",bytes);  }  //讀取方法,設(shè)定傳參是文件的String路徑,返回一個(gè)byte[]數(shù)組  public byte[] read(String str) {    byte[] bytes = new byte[0];    FileInputStream fis = null;    try {      fis = new FileInputStream(str);      int read;      bytes = new byte[1024000];      System.out.println("內(nèi)容讀取中...........");      while ((read = fis.read(bytes)) != -1) {        for (int i = 0; i < read; i++) {          System.out.print((char) bytes[i]);        }        System.out.println("\n內(nèi)容讀取完畢");      }      return bytes;    } catch (FileNotFoundException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    } finally {      try {        fis.close();      } catch (IOException e) {        e.printStackTrace();      }    }    return bytes;  }  //寫入方法,需要兩個(gè)參數(shù),一是寫入路徑,一是寫入內(nèi)容  public void write(String string,byte[] bytes) {    System.out.println("文件寫入中-----");    FileOutputStream fos = null;    try {      fos = new FileOutputStream(string);      try {        fos.write(bytes);      } catch (IOException e) {        e.printStackTrace();      }      System.out.println("文件寫入完畢");    } catch (FileNotFoundException e) {      e.printStackTrace();    }finally {      try {        fos.close();      } catch (IOException e) {        e.printStackTrace();      }    }  }}

上述就是小編為大家分享的Java中怎么實(shí)現(xiàn)文件讀取和寫入了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

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

AI