File
什么是File
file是文件的意思(文件,文件夹)对电脑中的文件进行操作
构造方法:
public File(String pathname)
pathname的意思是文件的路径
File方法:
作用 | 方法 |
---|---|
创建文件 | public boolean creatNewFile() |
创建文件夹 | public boolean mkdir() |
创建多层文件夹 | public boolean mkdirs() |
判断是否是文件 | public boolean isFile() |
判断是否是文件夹 | public boolean isDirectory() |
判断文件是否存在 | public boolean exists() |
获取文件大小 | public long length() |
获取某个文件夹下面的文件 | public String[] list() |
windows下的分隔符 \
linux下的分隔符 /
案例
在任何盘符下新建一个xiaozhao.txt文件
import java.io.File;
import java.io.IOException;
public class XiaoZhao01 {
public static void main(String[] args) throws IOException {
File file = new File("D:\\xiaozhao01.txt");
boolean creat = file.createNewFile();
System.out.println(creat);
}
}
字节流和字符流
字节流
字节输入流:FileInputStream;读取数据到内存
字节输入流: FileOutputStream;写数据到文件
FileInputStream
read():读取一个字节,每次读完以后,下次就会读取下一个字节
read(byte[] b):每次读取b.length个字节,读取到的字节存储到b数组中,数组里面放的就是读取到的数据,返回值是读取了多少个字节,如果读取完毕了,返回-1
案例:
练习字节输入输出流;
long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("D:\\xiaozhao1\\xiaozhao.txt",true);
// byte[] bytes = {99,98,55,45};
// byte[] bytes1 = "李大哥是个好人".getBytes();
// fos.write(bytes);
fis = new FileInputStream("D:\\Downloads\\microsofthevcvideoextensionx86x64.zip");
// int read = fis.read();
// int read1 = fis.read();
// System.out.println(read);
// System.out.println(read1);
byte[] bytes2 = new byte[1024];
int read = fis.read(bytes2);
while (read!=-1){
read = fis.read(bytes2);
System.out.println(Arrays.toString(bytes2));
}
long end = System.currentTimeMillis();
System.out.println("读取完毕需要"+ (end - start));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
使用缓冲流复制一个大型文件
long l = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("D:\\Downloads\\Navicat for MariaDB16.0.6.zip");
fos = new FileOutputStream("D:\\xiaozhao1\\xiaozhao\\xz\\2.zip");
byte[] bytes = new byte[1024*4];
int len = fis.read(bytes);
while (len!=-1){
fos.write(bytes);
len = fis.read(bytes);
System.out.println(Arrays.toString(bytes));
}
long l1 = System.currentTimeMillis();
System.out.println("需要"+(l1-l)+"ms");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
字符流
字符流的底层还是字节流,是专门处理文本的
字符输入流:FileReader
字符输出流:FileWriter