输入输出流
输入流
程序——通过写操作——uhihz——目的地
输出流
数据源——通过读操作——uhihz——程序
File类
文件是数据的集合,在Java中,使用java.io.File对文件进行操作
d:\\imooc\io\score.txt
d:\\imooc\set
均已存在
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) {
// 创建File对象,三种方法
/* File file1 = new File("d:\\imooc\\io\\score.txt"); */
/* File file1 = new File("d:\\imooc","io\\score.txt"); */
File file = new File("d:\\imooc");
File file1 = new File(file, "io\\score");
// 判断是文件还是目录,文件或目录存在的情况加才能判断!
System.out.println(file1.isDirectory());
System.out.println(file1.isFile());
// 创建文件
File file2 = new File("d:\\imooc\\at", "HashSet");
if (!file2.exists()) {
file2.mkdirs();
}
// 创建文件,它创建的是一个没有拓展名的文件
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
绝对路径和相对路径
绝对路径:从盘符开始的路径
相对路径:从当前路径开始的路径
import java.io.File;
import java.io.IOException;
public class FileDemo3 {
public static void main(String[] args) {
// 由绝对路径创建路径
File file = new File("d:\\zhihu\\java\\thread");
if (!file.exists()) {
file.mkdirs();
}
// 由绝对路径创建文件
File file1 = new File("d:\\zhihu\\java\\thread\\thread.txt");
if (!file1.exists()) {
try {
file1.createNewFile();// 只有在d:\\zhihu\\java\\thread存在的情况下,才能创建,否则报错!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("file1存在:" + file1.exists());
System.out.println("file1是绝对路径:" + file1.isAbsolute());
System.out.println("file1相对路径:" + file1.getPath());
System.out.println("file1绝对路径:" + file1.getAbsolutePath());
System.out.println("======================================");
// 由相对路径创建文件
File file2 = new File("..\\thread1.txt");// 两个点是转到上一级,转到上上级再加两个点和两个斜杠。
if (!file2.exists()) {
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("file2存在:" + file2.exists());
System.out.println("file2是绝对路径:" + file2.isAbsolute());
System.out.println("file2相对路径:" + file2.getPath());
System.out.println("file2绝对路径:" + file2.getAbsolutePath());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~·
运行结果:
file1存在:true
file1是绝对路径:true
file1相对路径:d:\zhihu\java\thread\thread.txt
file1绝对路径:d:\zhihu\java\thread\thread.txt
======================================
file2存在:true
file2是绝对路径:false
file2相对路径:..\thread1.txt
file2绝对路径:D:\Workspace\Java\Files\..\thread1.txt
由绝对路径创建的txt文件在D:\zhihu\java\thread中。其相对路径和绝对路径一样。
由相对路径创建的txt文件在D:\Workspace\Java中,也就是Files的bin文件夹的上级。其其相对路径和绝对路径不同。