Java實(shí)現(xiàn)文件讀取和寫入過程解析
需求說明
實(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í)例化對(duì)象 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(); } } } }
運(yùn)行結(jié)果
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Value注解支持對(duì)象類型ConfigurationProperties功能
這篇文章主要為大家介紹了Value注解支持對(duì)象類型ConfigurationProperties功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10Java網(wǎng)絡(luò)編程TCP實(shí)現(xiàn)文件上傳功能
這篇文章主要為大家詳細(xì)介紹了Java網(wǎng)絡(luò)編程TCP實(shí)現(xiàn)文件上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07Java獲取指定父節(jié)點(diǎn)、子節(jié)點(diǎn)的方法實(shí)現(xiàn)
在Java中,要獲取指定節(jié)點(diǎn)的父節(jié)點(diǎn)和子節(jié)點(diǎn),通常需要使用 DOM,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02Spring Boot 實(shí)現(xiàn)https ssl免密登錄(X.509 pki登錄)
這篇文章主要介紹了Spring Boot 實(shí)現(xiàn)https ssl免密登錄(X.509 pki登錄),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01Java BeanUtils.copyProperties的詳解
這篇文章主要介紹了Java BeanUtils.copyProperties的詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08spring boot中controller的使用及url參數(shù)的獲取方法
這篇文章主要介紹了spring boot中controller的使用及url參數(shù)的獲取方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-01-01Gradle的SpringBoot項(xiàng)目構(gòu)建圖解
這篇文章主要介紹了Gradle的SpringBoot項(xiàng)目構(gòu)建圖解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01