一、File类
File类只能获取文件的外部内容如文件名称等不能修改文件里面的内容。
File类 的相关方法:
1. CanWrite():返回文件是否可写。
CanRead():返回文件是否可读。
CompareTo(File pathname):检查指定文件路径间的顺序。
Delet():从文件系统内删除该文件。
DeleteOnExit():程序顺利结束时从系统中删除文件。
Exists():判断文件夹是否存在。
GetAbsoluteFile():返回文件的完整路径。
GetAbsolutePath():返回文件的完整路径。
GetName():返回文件名称。
GetParent():返回文件父目录路径。
GetPath():返回文件的潜在相对路径。
GetParentFile():返回文件所在文件夹的路径。
HashCode():返回文件哈希码。
IsDirectory():判断该路径指示的是否是文件。
IsFile():判断该路径指示的是否是文件。
LastModified() :返回文件的最后修改时间标志。
Length():返回文件长度。
List():返回文件和目录清单。
Mkdir():生成指定的目录。
RenameTo(File dest):更名文件。
SetReadOnly():将文件设置为可读。
ToString():返回文件状态的字符串。
ToURL():将文件的路径字符串转换成URL
GetCreationTime 读取创建时间
SetCreationTime 设置创建时间
2. GetLastAccessTime 读取最后访问时间
3. SetLastAccessTime 设置最后访问时间
GetLastWriteTime 读取最后修改时间
4. SetLastWriteTime设置最后修改时间
GetAttributes 读取文件属性
SetAttributes 设置文件属性
例如:
<span> </span>@Test
public void test(){
File file = new File("io/test.txt");
System.out.println(file.getName());
System.out.println(file.getPath());
}
打印结果
test.txt
io\test.txt
二、IO流
1.Io流是用来处理设备之间的数据传输
2.Java程序中,对于数据的输入/输出操作以流的方式进行
3.流的分类
1.按操作数据单位不同分为:字节流(8bit),字符流(16bit)
(1)字节流读入与写出为8bit ,以InputStream,outputStream结束
(2)字符流读入与写出为16bit ,以Reader,Writer结束(用于纯文本读取,传输)
2.按数据流的流向不同分为:输入流,输出流
3.按流的角色的不同分为:节点流,处理流
(1)节点流直接与数据源链接,是最基本的传输管道
(2)处理流在节点流上添加一层使传输更加快捷,便利,迅速
4.流的体系(蓝色的相对比较常用)
例:
1.简单的字节流读入:
@Test
public void testFileInputStream1() {
FileInputStream fileInputStream = null;
try {
//创建File对象,表明读取的对象
File file = new File("E://FileInputStream.txt");//读取文件为E盘目录下的FileInputStream.TXT文件
//运用节点流进行读取文本内容(汉字读取不了,只能通过字符流读取,调用方式基本想用)
fileInputStream = new FileInputStream(file);
int b;
while ((b = fileInputStream.read()) != -1) {
System.out.print(((char) b));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//由于IO流是在内存中开辟一部分控件,处理完成时需要关闭相应的流
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.比较复杂的缓冲流的读入写出:
<span style="white-space:pre"> </span>@Test
public void testBufferedInputOutputStream() {
//1.提供读入写出的文件
File file1 = new File("E://1.jpg");
File file2 = new File("E://2.jpg");
//3.将创建相应的节点流的对象作为形参传递给缓冲流的构造器中
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
//2.先创建相应的字节流:FileInputStream、FileOutputStream
FileInputStream fileInputStream = new FileInputStream(file1);
FileOutputStream fileOutputStream = new FileOutputStream(file2);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//具体的实现文件复制的操作
byte[] b = new byte[1024];
int len;
while ((len = bufferedInputStream.read(b)) != -1) {
bufferedOutputStream.write(b, 0, len);
bufferedOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭IO流
bufferedInputStream.close();
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}