輸入輸出流之File類
java.io包提供了許多的流類
字節輸入流:InPutStream 字符輸入流:Reader 字符輸出流:OutPutStream 字節輸出流:Writer
文件類File
三種創建File對象的方法
File(String filename);//創建的文件處於當前文件夾
File(String directoryPath,String filename);//directoryPath爲文件路徑
File(File dir,String filename);//dir是目錄文件,生成的文件在該目錄下
File類的一些常用方法
1.getName ——獲取文件名
2.canRead ——判斷文件是否可讀
3.canWrite ——判斷文件是否可寫
4.getName ——獲取文件名
5.exists ——判斷文件是否存在
6.length ——獲取文件長度
7.getAbsolutePath ——獲取絕對路徑
8.getParent ——獲取上級目錄
9.isFile ——判斷是普通文件還是目錄
10.isHidden ——判斷是否是隱藏文件
11.lastModified ——獲取最後修改日期(返回的是從1970年午夜到最後修改的毫秒數)
12.delete ——刪除當前文件
可執行文件
用Runtime聲明對象,然後調用getRuntime()方法創建;對象調用exec(String command)打開可執行文件
Runtime rt = Runtime.getRuntime();
rt.exec('C:/windows','Notic.exe');
調用delete刪除文件
file.delete();
文件字節輸入流:FileInputStream
兩種構造函數
FileInputStream(String name);//創建一個名字是name的流
FileInputStream(File file);//創建一個指向文件的輸入流
第二種方法創建輸入流可能會發生一些錯誤,比如指向的文件不存在了。所以應在try—catch語句中創建流,然後再捕捉異常。
讀取文件內容的例子
package com.zh;
import java.io.*;
public class Exampel {
public static void main(String[] args) {
int n = -1;
byte[] a = new byte[100];
try {
File f = new File("Example.java");
FileInputStream in = new FileInputStream(f);
while ((n=in.read(a,0,100))!=-1) {//讀取100個字節到a,從a的第0位置開始,並返回讀取的字節數,若讀取到文件末尾則返回-1
String s = new String(a,0,n);//把實際讀入的字節轉化爲字符串,注意n不可以寫成100
System.out.println(s);
}
in.close();//調用close關閉流
} catch (IOException e) {//捕捉異常
System.out.println("ERROR"+e);
}
}
}
輸出流FileOutputStream與輸入流類似
package com.zh;
import java.io.*;
public class Exampel {
public static void main(String[] args) {
byte[] a = "Hello".getBytes();//調用getBytes方法將字符轉換成字節
byte[] b = "Java".getBytes();
File file = new File("javaaaaaaa.txt");
try {
OutputStream out = new FileOutputStream(file);
System.out.println(file.getName()+"的大小是"+file.length()+"字節");
out.write(a);
out.close();
out = new FileOutputStream(file, true);//true表示流不會刷新文件,使得write可以在文件的末尾寫入數據
System.out.println(file.getName()+"的大小是"+file.length()+"字節");
out.write(b);
System.out.println(file.getName()+"的大小是"+file.length()+"字節");
out.close();
} catch (IOException e) {//捕捉異常
System.out.println("ERROR"+e);
}
}
}
運行結果:
javaaaaaaa.txt的大小是0字節
javaaaaaaa.txt的大小是5字節
javaaaaaaa.txt的大小是9字節