- 创建文件和目录
在当前工程工作路径下创建文件和文件夹
// create file
File file = new File("hello.txt");
try {
file.createNewFile();
} catch (IOException e) {
}
// create dir
File files = new File("files");
files.mkdir();
// 创建多级目录
File file1 = new File("parent/imgs");
file1.mkdirs();
在指定目录下创建文件,
目录必须要已经存在的,
否则将抛出 异常
java.io.IOException: No such file or directory
// :
路径分隔符
System.out.println(File.pathSeparator);
System.out.println(File.pathSeparatorChar);
// /
默认名称分隔符
System.out.println(File.separator);
System.out.println(File.separatorChar);
// 获取文件列表
File file2 = new File("/Users/benjamin/IntelliJIdeaProjects/IO/");
File[] listFiles = file2.listFiles();
- 字节流读取
单纯的字节流读取, 并把读取的字节流存储到一个字节数组中
// 限制在1kb大小的数组内
// 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; //全部读取的内容都使用temp接收
// 每次循环读取1个字节, 用temp临时存储读取得到的1个字节
while ((temp = in.read()) != -1) { //当没有读取完时,继续读取
// 把读取到的字节放到 字节数组b
b[len] = (byte) temp;
len++;
}
in.close();
System.out.println(new String(b, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream 从内存中读出数据到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);// 写入数据
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 写入字节流
flush()
OutputStream的flush()方法将所有写入到OutputStream的数据冲刷到相应的磁盘中。比如,如果输出流是FileOutputStream,那么写入到其中的数据可能并没有真正写入到磁盘中。即使所有数据都写入到了FileOutputStream,这些数据还是有可能保留在内存的缓冲区中。通过调用flush()方法,可以把缓冲区内的数据刷新到磁盘(或者网络,以及其他任何形式的目标媒介)中。
close()
当你结束数据写入时,需要关闭OutputStream。通过调用close()可以达到这一点。因为OutputStream的各种write()方法可能会抛出IO异常,所以你需要把调用close()的关闭操作方在finally块中执行。
- 不管流是不是被自动关闭, 我们都要在finally里手动关闭下
http://www.javapractices.com/topic/TopicAction.do?Id=8
https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
单纯的写入字节流
// 第1步、使用File类找到一个文件
File file3 = new File("hello2.txt"); // 声明File对象
// 第2步、通过子类实例化父类对象
FileOutputStream out = null;
try {
out = new FileOutputStream(file3);
// 第3步、进行写操作
String str = "Hello World!!!"; // 准备一个字符串
byte[] bytes = str.getBytes(); // 只能输出byte数组,所以将字符串变为byte数组
out.write(bytes); // 将内容输出,保存文件
} catch (IOException e) {
e.printStackTrace();
}finally {
// 把输出字节流关了
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取并写入字节字节流
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);// 写入数据
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭流
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 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。
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.
这句话是说, 不管是否出现异常, finally 语句一定会执行的,
即便是 在 try语句中执行了 方法的return 操作,
finally也还是会执行的, 所以 finally可以执行一些方法返回后的对代码的清空操作, 比如关闭流的操作。
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语句块中执行了虚拟机退出或者 线程终止也会导致finally语句不会执行。
删除文件和文件夹
- 删除文件
删除一个单独的文件
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();
}
}