日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JAVA|IO流的练习

發布時間:2023/12/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA|IO流的练习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

IO

  • 文件專屬
    • FileInputStream-FileOutputStream
    • FileReader-FileWriter
  • 轉化流
  • 緩沖流BufferedWriter-BufferedReader
  • 數據流專屬
  • 標準輸出流
  • File類
  • 文件拷貝

文件專屬

java.io.FileInputStream;java.io.FileOutputStream;java.io.FileReader;java.io.FileWriter;

要自行構造基本數據類型數組,來進行讀寫,如char[] int[]
前面兩個有Stream的是對字節做處理,可以處理文本文檔(所有能被寫字板打開的文件)、照片、視頻、音頻等。
要注意的一點是Stream在寫入一個文件時,要將文件目錄到具體文件名,不然將會拒絕訪問

然后每次對文件進行處理如寫入新的內容時,要對文件進行刷新——.flush()
在try語句中,最后要在finally處判斷文件是否為空,不為空時要將文件關閉,不然太占內存。

FileInputStream-FileOutputStream

字節流

package com.hdujavaTest.IOTest;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; /*文件專屬 * 讀取字節流 不僅能處理文本文檔 還可以讀取寫入圖像等格式 因為底層是對字節做處理 * * */ public class FileInputStreamTest01 {public static void main(String[] args) {//文件字節輸入流 讀取文件String txt="C:\\Users\\wish_cai\\Pictures\\大學\\psb.jpg";fileInputStreamfuntion(txt);//文件寫入/*String txtwrite="D:\\JAVA\\java_test\\IOTest02.txt";fileOutputStreamfuntion(txtwrite);*///復制 文本文檔 還行 但是涉及圖片就拒絕訪問//之前的復制 是FileOutputStream是涉及到文件夾路徑C:\Users\wish_cai\Pictures\作業,而FileOutputStream是寫入文件,所以要到具體的文件名String txtwritecopy="C:\\Users\\wish_cai\\Pictures\\作業\\新建文本文檔.jpg";fileCopy(txt,txtwritecopy);}//讀 輸入 硬盤到內存public static String fileInputStreamfuntion(String txt){//idea的默認路徑是在Project下//如果文件在其他模塊下,那么應該讀取時 模塊\\src(根據實際)\\文件名//文檔字節輸入流String s=null;FileInputStream fileInputStream=null;try{/*read()一次讀取一個字節 并以int形式返回*//*System.out.println("一次讀取一個字節 并以int形式返回");fileInputStream=new FileInputStream(txt);int filer;while ((filer=fileInputStream.read())!=-1){System.out.print(filer+" ");}*//*設置一個字節數組 用read(byte[]) 讀取字節,返回的是數量*///前面讀取完 之后需要重新新建一個FileInputStream對象//當最后數組不夠時,會覆蓋前面的,后面數組部分依舊會保留/*System.out.println('\n'+"設置一個字節數組 用read(byte[]) 讀取字節,返回的是數量:");fileInputStream=new FileInputStream(txt);byte[] bytesarr=new byte[6];int num;while ((num=fileInputStream.read(bytesarr))!=-1){//System.out.println(num);String s=new String(bytesarr,0,num);System.out.print(s);//System.out.print(new String(bytesarr,0,num));}*///.available();//表示還有多少字節可用//System.out.println('\n'+"表示還有多少字節可用");fileInputStream=new FileInputStream(txt);//fileInputStream.available();//表示還有多少字節可用System.out.println(fileInputStream.available());byte[] bytesarr2=new byte[fileInputStream.available()];fileInputStream.read(bytesarr2);String s2=new String(bytesarr2,0,bytesarr2.length);//System.out.println(s2);s=s2;//跳過多少字節/* System.out.println("跳過多少字節");fileInputStream=new FileInputStream(txt);fileInputStream.skip(8);byte[] bytesarr3=new byte[fileInputStream.available()];fileInputStream.read(bytesarr3);String s3=new String(bytesarr3,0,bytesarr3.length);System.out.println(s3);*///} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(fileInputStream!=null){try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}return s;}//寫 輸出 內存到硬盤 此處txt是我們的路徑public static void fileOutputStreamfuntion(String txt){FileOutputStream fileOutputStream=null;try{//謹慎使用 文件不存在 會自動新建立路徑和內容 文件之前存在 會覆蓋原內容fileOutputStream=new FileOutputStream(txt);System.out.println("輸入需要寫的內容:");Scanner scanner=new Scanner(System.in);String s=scanner.next();//String s="xinjianyigwenjianj.tsg";//s.getBytes();轉byte數組fileOutputStream.write(s.getBytes());//追加寫入fileOutputStream=new FileOutputStream(txt,true);System.out.println("追加寫入輸入需要寫的內容:");Scanner scanner1=new Scanner(System.in);String s2=scanner1.next();//String s="xinjianyigwenjianj.tsg";//s.getBytes();轉byte數組fileOutputStream.write(s2.getBytes());//前面追加//沒有快捷鍵,那我的想法是 先讀取之前文件的,然后寫入我想加在開頭的,然后再將之前的寫入//寫完之后要刷新fileOutputStream.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(fileOutputStream!=null){try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}}//文件的復制public static void fileCopy(String txtread,String txtwrite){FileInputStream fileInputStream=null;FileOutputStream fileOutputStream=null;try{//先輸入一個流對象fileInputStream=new FileInputStream(txtread);//讀fileOutputStream=new FileOutputStream(txtwrite);//寫//那就一邊讀 一邊寫int r;byte[] bytes=new byte[1024*1024];while ((r=fileInputStream.read(bytes))!=-1){fileOutputStream.write(bytes,0,r);}}catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(fileInputStream!=null){try{fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}if(fileOutputStream!=null){try{fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}} }

FileReader-FileWriter

字符流
用字符流 讀取文本文件
但是只能處理文本文檔

package com.hdujavaTest.IOTest;import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /*文件專屬 用字符流 讀取文本文件(能用記事本打開的) 復制文本文件 但是只能處理文本文檔 * */ public class Fileread01 {public static void main(String[] args) {/*String txt="D:\\JAVA\\java_test\\IOTest04copy.txt";FileReadfun(txt);*//*String txt1="C:\\Users\\wish_cai\\Pictures\\作業\\Write12.txt";FileWriterfun(txt1);*/String txt="D:\\JAVA\\java_test\\IOTest04copy.txt";String tet2="D:\\JAVA\\java_test\\IOrTow001.txt";CopyFile(txt,tet2);}public static void FileReadfun(String txt){FileReader fileReader=null;try{fileReader=new FileReader(txt);char[] chars=new char[30];int readnum;fileReader.read(chars);for (char c:chars) {System.out.print(c);}fileReader=new FileReader(txt);char[] chars2=new char[30];while ((readnum=fileReader.read(chars2))!=-1){System.out.println(new String(chars2,0,readnum));}fileReader=new FileReader(txt);while ((readnum=fileReader.read())!=-1){System.out.println(readnum);}fileReader=new FileReader(txt);}catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(fileReader!=null){try {fileReader.close();} catch (IOException e) {e.printStackTrace();}}}}//只能寫入普通文本 因為處理的是字符 ,前面流是處理字節public static void FileWriterfun(String txt){FileWriter fileWriter=null;try{fileWriter=new FileWriter(txt);System.out.println("input need your contents");Scanner scanner=new Scanner(System.in);String x=scanner.nextLine();fileWriter.write(x);fileWriter.flush();FileReadfun(txt);//要刷新之后才能讀取} catch (IOException e) {e.printStackTrace();} finally {if(fileWriter!=null){try {fileWriter.close();} catch (IOException e) {e.printStackTrace();}}}}//復制 只能拷貝普通文本 先讀取 再寫入public static void CopyFile(String readtxt,String writetxt){FileReader fileReader=null;FileWriter fileWriter=null;try{fileReader=new FileReader(readtxt);fileWriter=new FileWriter(writetxt);char[] rTow=new char[30];int numread=0;while ((numread=fileReader.read(rTow))!=-1){fileWriter.write(rTow);}fileWriter.close();FileReadfun(writetxt);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {}}}

轉化流

將字節流轉化為字符流

后面實用緩沖流的時候
我們可以不必自定義數組來輔助讀寫
而緩沖流的構造方法的參數是

public BufferedReader(Reader in) {this(in, defaultCharBufferSize);} public BufferedWriter(Writer out) {this(out, defaultCharBufferSize);}

可見是Reader和Writer類型,而在字符流和字節流中,只有字符流 FileWriter和FileReader是符合的。
如果我們想要在緩沖流的構造方法參數中傳入字節流 就要用到轉換流

OutputStreamWriter(new FileOutputStream("txt")) InputStreamReader(new FileInputStream("txt"));

緩沖流BufferedWriter-BufferedReader

**
緩沖流專屬

  • 不需要自定義char數組,byte數組,自帶緩沖
  • 將字符流 ————Reader下面的類FileReader 傳入包裝流的構造方法
  • FileReader extends InputStreamReader ;;;;; InputStreamReader extends Reader
  • 而如果是字節流 FileInputStream 如何傳入呢
  • 通過轉換流 轉化
  • 可以一行一行讀
    **
package com.hdujavaTest.IOTest;import java.io.*;/* * 緩沖流專屬 * 不需要自定義char數組,byte數組,自帶緩沖 * 將字符流 ————Reader下面的類FileReader 傳入包裝流的構造方法 * FileReader extends InputStreamReader ;;;;; InputStreamReader extends Reader * * 而如果是字節流 FileInputStream 如何傳入呢 * 通過轉換流 轉化* 可以一行一行讀 * */ public class Buffered01 {public static void main(String[] args) throws IOException {//緩沖流 讀 不需構造特定數組String txt="D:\\JAVA\\java_test\\IOTest\\out\\production\\IOTest\\com\\hdujavaTest\\IOTest\\Fileread01.class";Bufferread(txt);//緩沖流 寫 也不需構造特定數組String txtwrite="C:\\Users\\wish_cai\\Pictures\\作業\\tete.txt";Bufferwirte(txtwrite);}public static void Bufferread(String txt) throws IOException {//字符流傳入緩沖流BufferedReader bufferedReader=null;FileReader fileReader=new FileReader(txt);bufferedReader=new BufferedReader(fileReader);//String x=bufferedReader.readLine();String x;while ((x=bufferedReader.readLine())!=null){System.out.println(x);}bufferedReader.close();//字節流傳入緩沖流 通過轉化流FileInputStream in=new FileInputStream(txt);//********字節流InputStreamReader inputStreamReader=new InputStreamReader(in);//***********通過轉換流 轉化為字符流BufferedReader bufferedReader1=null;bufferedReader1=new BufferedReader(inputStreamReader);//*****傳入bufferedReader1.close();/*在new 后面的構造方法參數里 就是一個節點流* 用哪個構造方法 其引用就是一個包裝流* *//*合并寫*/BufferedReader bufferedReader2=new BufferedReader((new InputStreamReader(new FileInputStream(txt))));}public static void Bufferwirte(String txt) throws IOException {BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(txt));//字符流bufferedWriter.write("qweqhuiwfhais.!!!");//對文件作出修改 記得刷新bufferedWriter.flush();bufferedWriter.close();/*轉換流*/BufferedWriter bufferedWriter1=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txt,true)));//true 追加bufferedWriter1.write("\n"+"1111111111");bufferedWriter1.flush();bufferedWriter1.close();} }

數據流專屬

能夠保存數據類型+實際內容
且只能用對應的數據流讀寫
DataOutputStream

package com.hdujavaTest.IOTest;import java.io.*;public class DataStream01 {public static void main(String[] args) throws IOException {String txt1="D:\\bilibili\\JJDown\\Download\\Java零基礎教程視頻(適合Java 0基礎,Java初學入門)\\Data)";DataOutputStream(txt1);DataInputStream(txt1);}//數據字節輸入流 且帶有數據基本類型//且只能通過對應的DataInputstream打開public static void DataOutputStream(String txt) throws IOException {DataOutputStream dataOutputStream=new DataOutputStream(new FileOutputStream(txt));int a=1;int b=2;dataOutputStream.writeInt(a);dataOutputStream.writeInt(b);dataOutputStream.flush();dataOutputStream.close();}//讀取專屬數據流//而且要知道其專門的順序public static void DataInputStream(String txt) throws IOException {DataInputStream dataInputStream=new DataInputStream(new FileInputStream(txt));int x=dataInputStream.readInt();int y=dataInputStream.readInt();System.out.println(x);System.out.println(y);} }

標準輸出流

直接寫入到文件中

package com.hdujavaTest.IOTest;import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; //不需要手動關閉close public class PrintStream01 {public static void main(String[] args) throws FileNotFoundException {System.out.println("標準輸出流——print");PrintStream ps=System.out;ps.println("adsad");ps.println(1);ps.println(true);//寫入到固定路徑的文件中PrintStream ps1=new PrintStream(new FileOutputStream("D:\\bilibili\\JJDown\\Download\\Java零基礎教程視頻(適合Java 0基礎,Java初學入門)\\ad"));ps1.println(11111);ps1.println("ahuidqaas");} }

File類

File和四大家族沒什么關系,所以File不能完成文件的讀和寫
*File對象代表什么?

  • C:\ddd
  • C:\dasdf\asf\asfasf\asfa.txt
  • File對象可能是對應的目錄也可能是文件
  • File只是一個路徑的抽象表示形式
    在對于文件的處理上也十分便捷。
    提供了判斷文件路徑是否存在,不存在時新建,返回上一次修改的時間,刪除文件路徑、返回路徑的絕對形式、返回文件名、返回所有子文件的文件名(listFiles)等。
public class File01 {public static void main(String[] args) {File file=new File("C:\\Users\\wish_cai\\Pictures\\作業\\");System.out.println("文件是否存在:"+file.exists());System.out.println(file.length());//不存在 以文件形式新建File file1=new File("C:\\Users\\wish_cai\\Pictures\\作業\\xinjian");if(!file1.exists()) {try {file1.createNewFile();} catch (IOException e) {e.printStackTrace();}}File file2=new File("C:\\Users\\wish_cai\\Pictures\\a\\b\\c\\");if(!file2.exists())file2.mkdirs();//mkdirs建立多重目錄 否則 mkdir只能新建一個,在多重目錄要求下 沒有s將不會建立。} }

文件拷貝

java|IO流實現文件拷貝

package com.hdujavaTest.IOTest;import java.io.*;/***問題一:得到子文件夾的目錄之后,因為FileInputStream 需要讀到文件名 所以其拒絕訪問————遞歸調用* 涉及到 新建目錄** */ public class CopyFile01 {public static void main(String[] args) {File filesrc=new File("C:\\Users\\wish_cai\\Pictures\\作業");File filedest=new File("D:\\bilibili\\JJDown\\Download\\Java零基礎教程視頻(適合Java 0基礎,Java初學入門)\\copy\\");CopyDir(filesrc,filedest);}private static void CopyDir(File filesrc, File filedest){if(filesrc.isFile()){//是文件先拷貝,再跳出該次遞歸,否則即為目錄,進入目錄操作。//System.out.println(filesrc.getAbsolutePath());//是文件就進行拷貝處理copyfile(filesrc,filedest);return;}File temFile=null;File[] files=filesrc.listFiles();for (File f:files) {//文件或目錄File newdest=null;File newsrc=null;if(f.isDirectory()){/*當f是目錄中的一個子目錄時 進入*/String name=f.getName();String destDir=filedest.getAbsolutePath().endsWith("\\")?(filedest.getAbsolutePath()+name):(filedest.getAbsolutePath()+"\\"+name);/*System.out.println(destDir);*///在拷貝路徑中生成新的目錄newdest=new File(destDir);if(!newdest.exists())newdest.mkdirs();/*String srcDir=f.getAbsolutePath().endsWith("\\")?f.getAbsolutePath():(f.getAbsolutePath()+"\\");*/String srcDir=f.getAbsolutePath();System.out.println(srcDir);newsrc=new File(srcDir);temFile=newdest;//更新拷貝路徑CopyDir(newsrc,temFile);}//temFile=newdest;/*當目錄下的是一個文件時 進入下一次循環,然后直接拷貝*/if(!(f.isDirectory())){CopyDir(f,filedest);}}}private static void copyfile(File src,File dest){FileInputStream fileInputStream=null;FileOutputStream fileOutputStream=null;String txt=dest.getAbsolutePath().endsWith("\\")?dest.getAbsolutePath():(dest.getAbsolutePath()+"\\")+src.getName();System.out.println(txt);try{fileInputStream=new FileInputStream(src);fileOutputStream=new FileOutputStream(txt);byte[] bytes=new byte[1024*1024];int readcount;while ((readcount=fileInputStream.read(bytes))!=-1){fileOutputStream.write(bytes,0,readcount);}fileOutputStream.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(fileInputStream!=null) {try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}if(fileOutputStream!=null){try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}} }

總結

以上是生活随笔為你收集整理的JAVA|IO流的练习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。