- 創(chuàng)建文件和目錄
在當(dāng)前工程工作路徑下創(chuàng)建文件和文件夾
// create file
File file = new File("hello.txt");
try {
file.createNewFile();
} catch (IOException e) {
}
// create dir
File files = new File("files");
files.mkdir();
// 創(chuàng)建多級(jí)目錄
File file1 = new File("parent/imgs");
file1.mkdirs();
在指定目錄下創(chuàng)建文件,
目錄必須要已經(jīng)存在的,
否則將拋出 異常
java.io.IOException: No such file or directory
// :
路徑分隔符
System.out.println(File.pathSeparator);
System.out.println(File.pathSeparatorChar);
// /
默認(rèn)名稱分隔符
System.out.println(File.separator);
System.out.println(File.separatorChar);
// 獲取文件列表
File file2 = new File("/Users/benjamin/IntelliJIdeaProjects/IO/");
File[] listFiles = file2.listFiles();
- 字節(jié)流讀取
單純的字節(jié)流讀取, 并把讀取的字節(jié)流存儲(chǔ)到一個(gè)字節(jié)數(shù)組中
// 限制在1kb大小的數(shù)組內(nèi)
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1024
File file3 = new File("hello.txt");
// bytes
long length = file3.length();
try {
FileInputStream in = new FileInputStream(file3);
byte[] b = new byte[1024];
int len = 0;
int temp = 0; //全部讀取的內(nèi)容都使用temp接收
// 每次循環(huán)讀取1個(gè)字節(jié), 用temp臨時(shí)存儲(chǔ)讀取得到的1個(gè)字節(jié)
while ((temp = in.read()) != -1) { //當(dāng)沒有讀取完時(shí),繼續(xù)讀取
// 把讀取到的字節(jié)放到 字節(jié)數(shù)組b
b[len] = (byte) temp;
len++;
}
in.close();
System.out.println(new String(b, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream 從內(nèi)存中讀出數(shù)據(jù)到byte[]中然后,使用FileOutputStream寫入文件中。
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("hello.txt");
fos = new FileOutputStream("b.txt");
byte[] bytes = new byte[1024];
while ((fis.read(bytes)) != -1) {
fos.write(bytes);// 寫入數(shù)據(jù)
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 關(guān)閉流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 寫入字節(jié)流
flush()
OutputStream的flush()方法將所有寫入到OutputStream的數(shù)據(jù)沖刷到相應(yīng)的磁盤中。比如,如果輸出流是FileOutputStream,那么寫入到其中的數(shù)據(jù)可能并沒有真正寫入到磁盤中。即使所有數(shù)據(jù)都寫入到了FileOutputStream,這些數(shù)據(jù)還是有可能保留在內(nèi)存的緩沖區(qū)中。通過調(diào)用flush()方法,可以把緩沖區(qū)內(nèi)的數(shù)據(jù)刷新到磁盤(或者網(wǎng)絡(luò),以及其他任何形式的目標(biāo)媒介)中。
close()
當(dāng)你結(jié)束數(shù)據(jù)寫入時(shí),需要關(guān)閉OutputStream。通過調(diào)用close()可以達(dá)到這一點(diǎn)。因?yàn)镺utputStream的各種write()方法可能會(huì)拋出IO異常,所以你需要把調(diào)用close()的關(guān)閉操作方在finally塊中執(zhí)行。
- 不管流是不是被自動(dòng)關(guān)閉, 我們都要在finally里手動(dòng)關(guān)閉下
http://www.javapractices.com/topic/TopicAction.do?Id=8
https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
單純的寫入字節(jié)流
// 第1步、使用File類找到一個(gè)文件
File file3 = new File("hello2.txt"); // 聲明File對(duì)象
// 第2步、通過子類實(shí)例化父類對(duì)象
FileOutputStream out = null;
try {
out = new FileOutputStream(file3);
// 第3步、進(jìn)行寫操作
String str = "Hello World!!!"; // 準(zhǔn)備一個(gè)字符串
byte[] bytes = str.getBytes(); // 只能輸出byte數(shù)組,所以將字符串變?yōu)閎yte數(shù)組
out.write(bytes); // 將內(nèi)容輸出,保存文件
} catch (IOException e) {
e.printStackTrace();
}finally {
// 把輸出字節(jié)流關(guān)了
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
讀取并寫入字節(jié)字節(jié)流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("hello.txt");
fos = new FileOutputStream("b.txt");
byte[] bytes = new byte[1024];
while ((fis.read(bytes)) != -1) {
fos.write(bytes);// 寫入數(shù)據(jù)
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 關(guān)閉流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- try-catch-finall
https://www.ibm.com/developerworks/cn/java/j-lo-finally/
只有與 finally 相對(duì)應(yīng)的 try 語句塊得到執(zhí)行的情況下,finally 語句塊才會(huì)執(zhí)行。
The finally Block
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return,continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
這句話是說, 不管是否出現(xiàn)異常, finally 語句一定會(huì)執(zhí)行的,
即便是 在 try語句中執(zhí)行了 方法的return 操作,
finally也還是會(huì)執(zhí)行的, 所以 finally可以執(zhí)行一些方法返回后的對(duì)代碼的清空操作, 比如關(guān)閉流的操作。
public class Test {
public static void main(String[] args) {
System.out.println("return value of test(): " + test());
}
public static int test() {
int i = 1;
try {
System.out.println("try block");
return i;
} finally {
System.out.println("finally block");
}
}
}
打印:
try block
finally block
return value of test(): 1
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
這段話是說, 在 try和catch語句塊中執(zhí)行了虛擬機(jī)退出或者 線程終止也會(huì)導(dǎo)致finally語句不會(huì)執(zhí)行。
刪除文件和文件夾
- 刪除文件
刪除一個(gè)單獨(dú)的文件
File file3 = new File("b.txt");
if (file3.exists()) {
file3.delete();
}
- 刪除文件夾及文件夾下所有的文件
http://roufid.com/how-to-delete-folder-recursively-in-java/
/**
* Delete a file or a directory and its children.
* @param file The directory to delete.
* @throws IOException Exception when problem occurs during deleting the directory.
*/
private static void delete(File file) throws IOException {
for (File childFile : file.listFiles()) {
if (childFile.isDirectory()) {
delete(childFile);
} else {
if (!childFile.delete()) {
throw new IOException();
}
}
}
if (!file.delete()) {
throw new IOException();
}
}