IO 流
I:Inout( 输入流:读取数据到内存)
O:Output(输出流:将数据输出到文件)
逐个数据按顺序处理,类似水流进行流动,称为IO流
File类
文件和目录路径名的抽象表示形式。
java把电脑中的文件和文件夹(目录)封装为了一个File类,我们可以使用File类对文件和文件夹进行操作。
File其中方法:
作用 | 方法 | 返回值 |
---|---|---|
创建文件 | public boolean createNewFile() | 创建文件,如果文件存在就不创建,返回false |
创建文件夹 | public boolean mkdir() | boolean |
创建多层文件夹 | public boolean mkdirs() | boolean |
判断是否是文件夹 | public boolean isDirectory() | String |
判断是否是文件 | public boolean isFile() | String |
判断文件或目录是否存在 | public boolean exists() | String |
返回文件的长度,单位为字节 | lenght | long |
File file = new File("d:\\文件.txt");//在D盘创建一个txt类型的文件
boolean mkdir = file.mkdir();//创建一个文件夹
long length = file.length();//返回文件长度,单位为字节
System.out.println(file.exists());//判断文件/文件夹是否存在
字节流输出\输入
字节输入流(FileInputStream):
字节输出流(FinleOutputStream):
字符流输出\输入
字符流: 字符流的底层还是字节流, 字符流是专门处理文本的
字符输入流: FileReader
字符输出流: FileWriter
实例
package xinzhi;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo1 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
long start = System.currentTimeMillis();
try {
fis = new FileInputStream("D:\\idea..zip\\nb.txt");
fos = new FileOutputStream("E:\\idea321\\ss.txt");
byte[] bytes = new byte[1024 * 1024 * 2];
int len = 0;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes,0,len);
}
long end = System.currentTimeMillis();
System.out.println("拷贝完成" + (end-start) + "ms");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}