File類java
File類在java中表示(帶路徑的)文件或者目錄。linux
public static void main(String[] args) {數據庫
// 給定路徑建立File對象數組 // File file = new File("D:"+File.separator+"javatest"+File.separator+"a.txt");app File file = new File("d:\\javatest\\b.mp3");ui System.out.println(file);編碼
// 文件基本屬性spa System.out.println(file.canExecute());.net System.out.println(file.canRead());3d System.out.println(file.canWrite());
// 文件的建立、刪除 if(!file.exists()) {
boolean r; try { r = file.createNewFile(); if(r) { System.out.println("文件建立成功"); } } catch (IOException e) { e.printStackTrace(); } }
// 刪除文件 file.delete(); } |
建立文件時會拋出檢查時異常IOException
public static void main(String[] args) {
File file = new File("d:\\javatest\\a"); // File file = new File("a.txt");
// 獲取file的絕對路徑 System.out.println(file.getAbsolutePath()); // 獲取file的建立時的路徑字符串 System.out.println(file.getPath()); // 獲取文件或者目錄的名字 System.out.println(file.getName()); // 獲取文件或者目錄的父目錄 System.out.println(file.getParent());
} |
注意:若是file是相對路徑,相對路徑的當前路徑是工程目錄(java17)
public static void main(String[] args) {
File file = new File("d:\\javatest\\c\\d\\e");
if(!file.exists()) { boolean r;
try { // 一次只能建立一個目錄 // r = file.mkdir(); r = file.mkdirs(); if(r) { System.out.println("目錄建立成功"); } } catch (Exception e) { e.printStackTrace(); }
} } |
list():返回一個file表示的目錄中的子目錄或者文件,字符串數組類型
listFiles():返回一個file表示的目錄中的子目錄或者文件,File數組類型
public static void main(String[] args) {
// 需求:遍歷d:\javatest目錄 // list() File file = new File("d:\\javatest");
/* String[] list = file.list();
for (String str : list) { System.out.print(str); File f = new File(file.getPath()+"\\"+str); if(f.isDirectory()) { System.out.println(" 目錄"); }else { System.out.println(" 文件"); } }*/
// listFiles(); File[] listFiles = file.listFiles(); for (File f : listFiles) { System.out.print(f.getName()); if(f.isDirectory()) { System.out.println(" 目錄"); }else { System.out.println(" 文件"); } } } |
|
流(stream):流是一連串流動的數據(字節、字符),以先進先出的方式發送的信息的通道中。
輸入流
數據從源數據源流入程序的過程稱爲輸入流。能夠理解爲從源數據源讀取數據到程序的過程
輸出流
數據從程序流出到目的地的過程稱爲輸出流。能夠理解爲把數據從程序寫入目的地的過程
數據源通常指提供數據的原始媒介,通常常見有文件、數據庫、雲端、其餘硬件等能提供數據的媒介。
按照流向分爲輸入流和輸出流
按照處理單元分爲字節流和字符流
按照功能分爲節點流和轉換流。
InputStream/OutputStream
InputStream 是全部字節輸入流的抽象父類,提供了
read 讀取一個字節
read(byte[] buf) 讀取必定量的字節到緩衝區數組 buf中。
OutputStream 是全部字節輸出流的抽象父類,提供了
write() 寫入一個字節
write(byte[] buf) 寫入必定量的字節到輸出流
FileInputStream 文件字節輸入流,專門用於從文件中讀取字節到程序內存中。
FileOutputStream 文件字節輸出流,專門用於從內存中寫入字節到文件中。
需求:從文件讀取一個字節
public static void main(String[] args) {
// 需求:讀取一個文件中的一個字節 File file = new File("d:\\javatest\\a.txt");
// 【1】建立管道 FileInputStream in = null;
try { in = new FileInputStream(file);
// 【2】從管道讀取一個字節 /* int t; t = in.read(); t = in.read(); t = in.read(); t = in.read(); */ // System.out.println(t);
// 循環讀取一個字節 int t; StringBuilder sb = new StringBuilder(); while( (t=in.read()) != -1 ) { sb.append((char)t); }
System.out.println(sb.toString());
} catch (FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }
// 【3】關閉流管道 try { in.close(); } catch (IOException e) { e.printStackTrace(); } } |
一次讀取多個字節
public static void main(String[] args) {
// 需求:一次讀取多個字節 File file = new File("d:\\javatest\\a.txt");
// 【1】建立管道 FileInputStream in = null;
try { in = new FileInputStream(file);
// 【2】從管道讀取多個字節到緩衝區 /* byte[] buf = new byte[5]; int len; len = in.read(buf); len = in.read(buf); len = in.read(buf); len = in.read(buf);
for(byte b:buf) { System.out.print((char)b+"\t"); } System.out.println(len); */
// 經過循環讀取文件 byte[] buf = new byte[5]; int len; StringBuilder sb = new StringBuilder(); while( (len=in.read(buf)) != -1 ) { // 讀取的內容是原始二進制流,須要根據編碼的字符集解碼成對於字符 String str = new String(buf,0,len); sb.append(str); } System.out.println(sb.toString());
} catch (FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }
// 【3】關閉流管道 try { in.close(); } catch (IOException e) { e.printStackTrace(); } } |
需求:按照指定編碼寫入文件
public static void main(String[] args) {
File file = new File("d:\\javatest\\c.txt");
FileOutputStream out = null;
try { // 【1】建立輸出流管道 out = new FileOutputStream(file);
// 【2】寫入數據到管道中 // 一次寫入一個字節 /* out.write(97); out.write(98); out.write(99); */
// 一次寫入多個字節 String str = "hello world"; // gbk /* byte[] buf = str.getBytes(); out.write(buf); */
byte[] buf = str.getBytes("UTF-8"); out.write(buf);
System.out.println("寫入完成!");
} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
// 【3】關閉流 try { out.close(); } catch (IOException e) { e.printStackTrace(); } } |
注意:
[1]字符串寫入文件時必定會存在編碼問題
[2]使用utf8編碼寫入文件時,若是不含中文時,win系統會對文件的編碼形成誤判。
[3] 經過字節流寫入文件時,向管道寫入一個字節,該字節當即寫入文件中。
總結
InputStream/OutputStream 用於字節的讀寫。主要用於讀取二進制文件(圖片、音頻、視頻),也能夠讀取文件性文件。
需求:請把d:\\javatest\\logo.png 複製到工程目錄中,並顯示覆制進度。
public static void main(String[] args) throws FileNotFoundException,IOException {
File oriFile = new File("d:\\javatest\\logo.jpg"); File toFile = new File("logo.jpg");
long totalLen = oriFile.length(); // 文件大小 long cpyedLen = 0; // 已複製完成的大小 float progress = 0.0f;
FileInputStream in = new FileInputStream(oriFile); FileOutputStream out = new FileOutputStream(toFile);
// 一次讀取1kb byte[] buf = new byte[512]; int len; while( (len=in.read(buf)) != -1) { out.write(buf, 0, len); cpyedLen += len; progress = cpyedLen*1.0f/totalLen; System.out.println(progress);
}
in.close(); out.close();
System.out.println("複製完成!");
} |
Reader 是字符輸入流的抽象父類,提供了
read 一次讀取一個字符
read(char[] cbuf) 一次讀取多個字符到字符緩衝區cbuf,返回長度表示讀取的字符個數。
Writer 是字符輸出流的抽象父類,提供了
write
write(char[] cbuf)
write(string)
FileReader 文件字符輸入流,專門用於讀取默認字符編碼文本性文件。
FileWriter 文件字符輸出流,專門用於寫入默認字符編碼的文本性文件。爲了提升效率,FileWriter內部存在一個字節緩衝區,用於對待寫入的字符進行統一編碼到字節緩衝區,必定要在關閉流以前,調用flush方法刷新緩衝區。
需求:一次讀取一個字符/多個字符到cbuf
public static void main(String[] args) throws IOException {
File file = new File("d:\\javatest\\d.txt");
FileReader reader = new FileReader(file);
// 【1】一次讀取一個字符 /* int c; c = reader.read(); c = reader.read(); c = reader.read(); c = reader.read(); c = reader.read(); System.out.println((char)c); */
// 【2】一次讀取多個字符到cbuf中 /* char[] cbuf = new char[2]; int len; len = reader.read(cbuf); len = reader.read(cbuf); len = reader.read(cbuf); len = reader.read(cbuf); System.out.println(Arrays.toString(cbuf)); System.out.println(len); */
char[] cbuf = new char[2]; int len; StringBuilder sb = new StringBuilder(); while( (len=reader.read(cbuf)) != -1 ) { sb.append(cbuf,0,len); }
System.out.println(sb); } |
需求:寫入字符到文件中
public static void main(String[] args) throws IOException {
File file = new File("d:\\javatest\\f.txt");
FileWriter writer = new FileWriter(file);
// 【1】一次寫入一個字符 /*writer.write('中'); writer.write('國');*/
// 【2】一次寫入多個字符 /*char[] cbuf = {'h','e','l','l','o','中','國'}; writer.write(cbuf);*/
// 【3】一次寫入一個字符串 String str = "hello你好"; writer.write(str);
// 刷新字節緩衝區 writer.flush();
// 關閉流通道 writer.close();
System.out.println("寫入完成"); } |
InputStreamReader 繼承於Reader,是字節流通向字符流的橋樑,能夠把字節流按照指定編碼 解碼 成字符流。
OutputStreamWriter 繼承於Writer,是字符流通向字節流的橋樑,能夠把字符流按照指定的編碼 編碼 成字節流。
需求:寫入utf8文件
/** * 把一個字符串以utf8編碼寫入文件 */ public class Test01 { public static void main(String[] args) throws IOException {
String str = "hello中國"; File file = new File("d:\\javatest\\g.txt");
// 【1】建立管道 FileOutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
// 【2】寫入管道 writer.write(str);
// 【3】刷新緩衝區 writer.flush();
// 【4】關閉管道 out.close(); writer.close();
System.out.println("寫入完成"); } } |
需求:讀取utf8文件
/** * 讀取utf8編碼的文本文件 */ public class Test01 { public static void main(String[] args) throws IOException {
File file = new File("d:\\javatest\\g.txt");
// 【1】創建管道 FileInputStream in = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(in, "UTF-8");
char[] cbuf = new char[2]; int len;
StringBuilder sb = new StringBuilder(); while( (len=reader.read(cbuf))!=-1 ) { sb.append(cbuf, 0, len); } System.out.println(sb.toString());
} } |
注意:
[1]win平臺默認的utf8編碼的文本性文件帶有BOM,java轉換流寫入的utf8文件不帶BOM。因此用java讀取手動建立的utf8文件會出現一點亂碼(?hello中國,?是bom致使的)
[2] 一句話:用字符集編碼,必定用字符集解碼!!
FileReader = InputStreamReader + GBK
package cn.sxt07.outputstreamwriter;
import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader;
/** * 讀取一個gbk編碼的文本性文件 */ public class Test02 { public static void main(String[] args) throws IOException {
File file = new File("d:\\javatest\\f.txt");
// 【1】創建管道 /* * FileInputStream in = new FileInputStream(file); * InputStreamReader reader = new InputStreamReader(in, "GBK"); */
FileReader reader = new FileReader(file);
char[] cbuf = new char[2]; int len;
StringBuilder sb = new StringBuilder(); while( (len=reader.read(cbuf))!=-1 ) { sb.append(cbuf, 0, len); }
reader.close();
System.out.println(sb.toString()); } }
|
BufferedReader 繼承於Reader,提供了
read
read(char[] cbuf)
readLine() 用於讀取一行文本,實現對文本的高效讀取。
BufferedReader 初始化時須要一個reader,本質上BufferedReader在reader的基礎上增長readLine()的功能。
BufferedWriter繼承於Writer,提供了
write
write(char[] cbuf)
write(string)
newline() 寫入一個行分隔符。
需求:讀取一首詩
public static void main(String[] args) throws IOException {
// 按行讀取gbk文本性文件
File file = new File("d:\\javatest\\i.txt");
// 【1】建立管道 FileReader reader = new FileReader(file); BufferedReader br = new BufferedReader(reader);
// 【2】讀取一行 /* String line = br.readLine(); line = br.readLine(); line = br.readLine(); line = br.readLine(); */
String line; while( (line=br.readLine()) != null) { System.out.println(line); } } |
需求:以gbk編碼寫入一首詩到文件
public static void main(String[] args) throws IOException {
File file = new File("d:\\javatest\\j.txt");
// 【1】建立gbk管道 FileWriter writer = new FileWriter(file); BufferedWriter bw = new BufferedWriter(writer);
// 【2】寫入一行 bw.write("窗前明月光,"); bw.newLine();
bw.write("疑似地上霜。");
// for win // bw.write("\r\n");
// for unix/linux/mac // bw.write("\n");
bw.write("舉頭望明月,"); bw.newLine();
// 【3】flush bw.flush();
// 【4】關閉管道 bw.close(); writer.close(); } |
需求:以utf8編碼高效寫入文件
/** * 以utf8寫入一首詩 * @author Administrator * */ public class Test02 { public static void main(String[] args) throws IOException {
File file = new File("d:\\javatest\\j-utf8.txt");
// 【1】建立utf8管道 FileOutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); BufferedWriter bw = new BufferedWriter(writer);
// 【2】寫入一行 bw.write("窗前明月光,"); bw.newLine();
bw.write("疑似地上霜。");
// for win bw.write("\r\n");
// for unix/linux/mac // bw.write("\n");
bw.write("舉頭望明月,"); bw.newLine();
// 【3】flush bw.flush();
// 【4】關閉管道 bw.close(); writer.close(); } } |