Java入門系列-22-IO流

File類的使用

Java程序如何訪問文件?通過 java.io.File 類

使用File類需要先創建文件對象 File file=new File(String pathname);,創建時在構造函數中指定物理文件或目錄,然后通過文件對象的方法操作文件或目錄的屬性。

\ 是特殊字符,要使用需要轉義 \\

File 類常用方法

方法名稱說明
boolean exists()判斷文件或目錄是否存在
boolean isFile()判斷是否是文件
boolean isDirectory()判斷是否是目錄
String getPath()返回此對象表示的文件的相對路徑名
String getAbsolutePath()返回此對象表示的文件的絕對路徑
String getName()返回此對象指定的文件或目錄
boolean createNewFile()創建名稱的空文件,不創建文件夾
long length()返回文件的長度,單位為字節,文件不存在則返回0L
File[] listFiles()返回一個抽象路徑名數組,這些路徑名表示此抽象路徑名表示的目錄中的文件。
static File[] listRoots()列出可用文件系統根
boolean mkdirs()創建此抽象路徑名指定的目錄,包括所有必需但不存在的父目錄。

使用示例:

import java.io.File;
import java.io.IOException;public class TestFile {public static void main(String[] args) {//創建File對象 傳入文件的路徑File file=new File("D:\\a.txt");//創建File對象 傳入文件夾的路徑File dir=new File("D:/word");//判斷是否存在if(file.exists()) {if(file.isFile()) {//getName()獲取名字System.out.println(file.getName()+" 是文件");}else if(file.isDirectory()){System.out.println(file.getName()+" 是目錄");}            }else {System.out.println(file.getName()+" 不存在!");try {//創建文件file.createNewFile();System.out.println("文件大小:"+file.length()+" 字節");} catch (IOException e) {e.printStackTrace();}}if(dir.exists()) {if(dir.isFile()) {System.out.println(dir.getName()+" 是文件");}else if(dir.isDirectory()) {System.out.println(dir.getName()+" 是文件夾");//絕對路徑System.out.println(dir.getAbsolutePath());}            }else {System.out.println(dir.getName()+" 不存在!");//創建目錄dir.mkdirs();}}
}

:指一連串流動的字符,是以先進先出方式發送信息的通道

輸入流:源數據流向程序(讀)

輸入流:程序中的數據流向目標數據源(寫)

Java流的分類

按流向

  • 輸出流(OutputStream和Writer作為基類)
  • 輸入流(InputStream和Reader作為基類)

輸入輸出流是相對于計算機內存來說的

按照處理數據單元劃分

  • 字節流

    • 字節輸入流(InputStream基類)
    • 字節輸出流(OutputStream基類)
  • 字符流

    • 字符輸入流(Reader基類)
    • 字符輸出流(Writer基類)

字節流是8位(1B)通用字節流,字符流是16位(2B)Unicode字符流

字節流

FileInputStream 是 InputStream 的子類

InputStream 類常用方法

方法名稱說明
int read()從輸入流中讀取數據的下一個字節。返回0到255的int值,如果到達流的末尾,則返回-1
int read(byte[] b)從輸入流中讀取一定數量的字節,并將其存儲在緩沖區數組 b 中。返回讀入緩沖區的總字節數,如果達到末尾則返回-1
int read(byte[] b,int off,int len)將輸入流中最多 len 個數據字節讀入 byte數組
void close()關閉此輸入流并釋放與該流關聯的所有系統資源
int available()返回此輸入流下一個方法調用可以不受阻塞地從此輸入流讀取的估計字節數

FileInputStream 類常用構造方法

名稱說明
FileInputStream(File file)通過打開一個到實際文件的連接來創建一個 FileInputStream,該文件通過文件系統中的 File 對象 file 指定。
FileInputStream(String name)通過打開一個到實際文件的連接來創建一個 FileInputStream,該文件通過文件系統中的路徑名 name 指定。

使用 FileInputStream 讀取文件

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;public class TestFileInputStream {public static void main(String[] args) {FileInputStream fis=null;try {fis=new FileInputStream("D:\\a.txt");//讀取結果存入StringBufferStringBuffer sb=new StringBuffer();System.out.println("預計讀取:"+fis.available()+"字節");//記錄每次讀取的長度int len=0;//緩沖區字節數組byte[] buff=new byte[1024];while((len=fis.read(buff))!=-1) {System.out.println("還剩余:"+fis.available()+"字節");sb.append(new String(buff,0,len));}System.out.println("結果:");System.out.println(sb);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (fis!=null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
}

FileOutputStream 是 OutputStream 的子類

OutputStream 類常用方法

方法名稱說明
void write(int c)將制定的字節寫入此輸出流
void write(byte[] buf)將 b.length 個字節從指定的 byte 數組寫入此輸入流
void write(byte[] b,int off,int len)將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此輸出流
void close()關閉此輸出流并釋放與此流有關的所有系統資源

FileOutputStream的構造方法

名稱說明
FileOutputStream(File file)創建一個向指定 File 對象表示的文件中寫入數據的文件輸出流
FileOutputStream(String name)創建一個向具有指定名稱的文件中寫入數據的輸出文件流
FileOutputStream(String name,boolean append)第二個參數為 true,則將字節寫入文件末尾處,而不是寫入文件開始處

使用 FileOutputStream 寫文件

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class TestFileOutputStream {public static void main(String[] args) {FileOutputStream fos=null;try {//創建輸出流對象fos=new FileOutputStream("D:\\c.txt");//要輸出的字符String str="hello world 你好";//將字符串轉成字節數組并寫入到流中fos.write(str.getBytes());//刷新流fos.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (fos!=null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}
}

字符流

上面的內容我們看到,字節流不能直接操作字符,所以操作字符用字符流。

FileReader 是 Reader 的子類

Reader 類常用方法

方法名稱說明
int read()讀取單個字符
int read(char[] c)將字符讀入數組
read(char[] c,int off,int len)將字符讀入數組的某一部分
void close()關閉該流并釋放與之關聯的所有資源

使用 FileReader 讀取文本文件

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;public class TestReader {public static void main(String[] args) {Reader r=null;try {//創建FileReader對象r=new FileReader("D:\\a.txt");//字符緩沖數組char[] chrs=new char[512];//記錄每次讀取的個數int len=0;//循環讀取while((len=r.read(chrs))!=-1) {String str=new String(chrs, 0, len);System.out.println(str);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (r!=null) {try {r.close();} catch (IOException e) {e.printStackTrace();}}}}
}

FileWriter 是 Writer 的子類

Writer 類常用方法

方法名稱說明
write(String str)寫入字符串
write(String str,int off,int len)寫入字符串的某一部分
void close()關閉此流,但要先刷新它
void flush刷新該流的緩沖

使用 FileWriter 寫入文本文件

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;public class TestWriter {public static void main(String[] args) {Writer w=null;try {//創建字符輸出流w=new FileWriter("D:\\msg.txt");String msg="hello every bady 兄嘚";//將字符串寫入到流中w.write(msg);w.flush();} catch (IOException e) {e.printStackTrace();}finally {if (w!=null) {try {w.close();} catch (IOException e) {e.printStackTrace();}}}}
}

緩沖字符流

如果頻繁的對字符進行讀寫操作,墻裂建議使用緩沖!

BufferedReader 類帶有緩沖區,可以先把一批數據讀到緩沖區,接下來的讀操作都是從緩沖區內獲取數據,避免每次都從數據源讀取數據進行字符編碼轉換,從而提高讀取操作的效率。

使用BufferedReader讀取文本文件

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class TestBufferedReader {public static void main(String[] args) {FileReader reader=null;BufferedReader br=null;try {//創建字符讀入流reader=new FileReader("D:\\a.txt");//將字符讀入流包裝成字符緩沖流br=new BufferedReader(reader);//記錄每行讀入的內容String line=null;//用于拼接保存每行讀入的內容StringBuffer content=new StringBuffer();while ((line=br.readLine())!=null) {content.append(line+"\n");}System.out.println("所有內容:");System.out.println(content);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {try {if (reader!=null) {reader.close();}if (br!=null) {br.close();}} catch (Exception e) {e.printStackTrace();}}}
}

BufferedReader 是 Reader 的子類,帶有緩沖區,特有方法 readLine() 按行讀取內容

BufferedWriter 類帶有緩沖區,與BufferedReader的方向正好相反,BufferedWriter 是把一批數據寫到緩沖區,當緩沖區滿的時候,再把緩沖區的數據寫到字符輸出流中。避免每次都執行物理寫操作,提高寫操作的效率。

使用 BufferedWriter 寫文件

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;public class TestBufferedWriter {public static void main(String[] args) {FileWriter writer=null;BufferedWriter bw=null;try {writer=new FileWriter("D:\\out.txt");bw=new BufferedWriter(writer);bw.write("hello");//內容換行bw.newLine();bw.write("world");} catch (IOException e) {e.printStackTrace();}finally {try {if (bw!=null) {bw.close();}if (writer!=null) {writer.close();}} catch (IOException e) {e.printStackTrace();}}}
}

關閉流的順序與創建流的順序相反

數據流

DataInputStream 類

  • FileInputStream 的子類
  • 與 FileInputStream 類結合使用讀取二進制文件

DataOutputStream 類

  • FileOutputStream 的子類
  • 與 FileOutputStream 類結合使用寫二進制文件

使用數據流復制圖片

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class TestCopy {public static void main(String[] args) {//文件輸入流FileInputStream fis=null;//數據輸入流(包裝fis得到)DataInputStream dis=null;//文件輸出流FileOutputStream fos=null;//數據輸出流(包裝fos得到)DataOutputStream dos=null;try {fis=new FileInputStream("D:\\a.jpg");dis=new DataInputStream(fis);fos=new FileOutputStream("F:\\b.jpg");dos=new DataOutputStream(fos);//緩沖數組byte[] buff=new byte[1024];//記錄每次讀取的字節個數int len=0;//循環讀入while((len=dis.read(buff))!=-1) {//循環寫入len個字節dos.write(buff,0,len);}System.out.println("完成");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {try {if (dis!=null) {dis.close();}if (dos!=null) {dos.close();}} catch (IOException e) {e.printStackTrace();}}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/389296.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389296.shtml
英文地址,請注明出處:http://en.pswp.cn/news/389296.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

缺了一部分

學Java好多年,也參與一次完整項目,覺得讓自己寫項目寫不出來,總覺得缺了一部分。 在這方面愚笨,不知道缺在哪里。以前覺得是知識不夠牢固,于是重復去學,發現就那些東西。如果沒有業務來熟悉的話&#xff0c…

卷積神經網絡——各種網絡的簡潔介紹和實現

各種網絡模型:來源《動手學深度學習》 一,卷積神經網絡(LeNet) LeNet分為卷積層塊和全連接層塊兩個部分。下面我們分別介紹這兩個模塊。 卷積層塊里的基本單位是卷積層后接最大池化層:卷積層用來識別圖像里的空間模…

數據中臺是下一代大數據_全棧數據科學:下一代數據科學家群體

數據中臺是下一代大數據重點 (Top highlight)Data science has been an eye-catching field for many years now to young individuals having formal education with a bachelors, masters or Ph.D. in computer science, statistics, business analytics, engineering manage…

net如何判斷瀏覽器的類別

回復:.net如何判斷瀏覽器的類別?瀏覽器型號:Request.Browser.Type 瀏覽器名稱:Request.Browser.browser 瀏覽器版本:Request.Browser.Version 瀏覽器Cookie:Request.Browser.Cookies 你的操作系統:Request…

AVS 端能力模塊

Mark 轉載于:https://www.cnblogs.com/clxye/p/9939333.html

pwn學習之四

本來以為應該能出一兩道ctf的pwn了,結果又被sctf打擊了一波。 bufoverflow_a 做這題時libc和堆地址都泄露完成了,卡在了unsorted bin attack上,由于delete會清0變量導致無法寫,一直沒構造出unsorted bin attack,后面根…

優化算法的簡潔實現

動量法 思想: 動量法使用了指數加權移動平均的思想。它將過去時間步的梯度做了加權平均,且權重按時間步指數衰減。 代碼: 在Gluon中,只需要在Trainer實例中通過momentum來指定動量超參數即可使用動量法。 d2l.train_gluon_ch7…

北方工業大學gpa計算_北方大學聯盟倉庫的探索性分析

北方工業大學gpa計算This is my firts publication here and i will start simple.這是我的第一篇出版物,這里我將簡單介紹 。 I want to make an exploratory data analysis of UFRN’s warehouse and answer some questions about the data using Python and Pow…

泰坦尼克數據集預測分析_探索性數據分析-泰坦尼克號數據集案例研究(第二部分)

泰坦尼克數據集預測分析Data is simply useless until you don’t know what it’s trying to tell you.除非您不知道數據在試圖告訴您什么,否則數據將毫無用處。 With this quote we’ll continue on our quest to find the hidden secrets of the Titanic. ‘The …

各種數據庫連接的總結

SQL數據庫的連接 return new SqlConnection("server127.0.0.1;databasepart;uidsa;pwd;"); oracle連接字符串 OracleConnection oCnn new OracleConnection("Data SourceORCL_SERVER;USERM70;PASSWORDmmm;");oledb連接數據庫return new OleDbConnection…

關于我

我是誰? Who am I?這是個哲學問題。。 簡單來說,我是Light,一個靠前端吃飯,又不想單單靠前端吃飯的Coder。 用以下幾點稍微給自己打下標簽: 工作了兩三年,對,我是16年畢業的90后一直…

L1和L2正則

https://blog.csdn.net/jinping_shi/article/details/52433975轉載于:https://www.cnblogs.com/zyber/p/9257843.html

基于PyTorch搭建CNN實現視頻動作分類任務代碼詳解

數據及具體講解來源: 基于PyTorch搭建CNN實現視頻動作分類任務 import torch import torch.nn as nn import torchvision.transforms as T import scipy.io from torch.utils.data import DataLoader,Dataset import os from PIL import Image from torch.autograd…

missforest_missforest最佳丟失數據插補算法

missforestMissing data often plagues real-world datasets, and hence there is tremendous value in imputing, or filling in, the missing values. Unfortunately, standard ‘lazy’ imputation methods like simply using the column median or average don’t work wel…

華碩猛禽1080ti_F-22猛禽動力回路的視頻分析

華碩猛禽1080tiThe F-22 Raptor has vectored thrust. This means that the engines don’t just push towards the front of the aircraft. Instead, the thrust can be directed upward or downward (from the rear of the jet). With this vectored thrust, the Raptor can …

聊天常用js代碼

<script languagejavascript>//轉意義字符與替換圖象以及字體HtmlEncode(text)function HtmlEncode(text){return text.replace(//"/g, &quot;).replace(/</g, <).replace(/>/g, >).replace(/#br#/g,<br>).replace(/IMGSTART/g,<IMG style…

溫故而知新:柯里化 與 bind() 的認知

什么是柯里化?科里化是把一個多參數函數轉化為一個嵌套的一元函數的過程。&#xff08;簡單的說就是將函數的參數&#xff0c;變為多次入參&#xff09; const curry (fn, ...args) > fn.length < args.length ? fn(...args) : curry.bind(null, fn, ...args); // 想要…

OPENVAS運行

https://www.jianshu.com/p/382546aaaab5轉載于:https://www.cnblogs.com/diyunpeng/p/9258163.html

Memory-Associated Differential Learning論文及代碼解讀

Memory-Associated Differential Learning論文及代碼解讀 論文來源&#xff1a; 論文PDF&#xff1a; Memory-Associated Differential Learning論文 論文代碼&#xff1a; Memory-Associated Differential Learning代碼 論文解讀&#xff1a; 1.Abstract Conventional…

大數據技術 學習之旅_如何開始您的數據科學之旅?

大數據技術 學習之旅Machine Learning seems to be fascinating to a lot of beginners but they often get lost into the pool of information available across different resources. This is true that we have a lot of different algorithms and steps to learn but star…