文件对象
package com.bilibili;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
File file = new File("test.txt");
System.out.println(file.getAbsolutePath());
System.out.println(file.mkdirs());
File file1 = new File("test.txt/test1.txt");
try {
System.out.println(file1.createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
File file2 = new File("copy.txt");
System.out.println(file2.length());
System.out.println(file2.delete());
File file3 = new File("D:");
System.out.println(file3.getFreeSpace()/1024/1024/1024 + "G");
File file4 = new File(".");
for (String s: file4.list()) {
System.out.println(s);
}
}
}
文件拷贝带进度条
package com.bilibili;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
File file = new File("NeverBeFar.mp4");
try(FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("copy.mp4")){
byte[] buffer = new byte[1024 * 1024];
int len ;
long total = file.length(),sum = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
sum += len;
System.out.println("文件已经拷贝了 " + (sum * 100 / total) + "%");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
缓冲流
package com.bilibili;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try(BufferedInputStream stream = new BufferedInputStream(new FileInputStream("test.txt/test1.txt"))){
System.out.println((char) stream.read());
stream.mark(0);
System.out.println((char) stream.read());
stream.reset();
System.out.println((char) stream.read());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}