File类
创建一个文件 ,一个File类的对象,表示了磁盘上的文件或目录。
class FileTest {
public static void main(String[] args) throws IOException{
File f = new File("1.txt");
//创建一个文件
f.createNewFile();
}
}
在eclipse工程目录下新建一个文件成功
创建一个目录
class FileTest {
public static void main(String[] args) throws IOException{
File f = new File("1.txt");
//f.createNewFile();
//创建目录
f.mkdir();
}
}
结果:
创建文件成功
如果想在指定的绝对路径创建文件,在File类构造函数时注意
根据window系统的绝对路径创建文件
注意转义字符
class FileTest {
public static void main(String[] args) throws IOException{
//绝对路径创建文件,本意是'\'作为目录的分隔符,在windows系统要在'\'加一个'\'
File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
f.createNewFile();
}
}
结果在指定路径生成了1.txt文件
问题引出:因为在linux目录分隔符是正斜杠’/’程序移植到linux平台就不会识别目录分隔符了,我们要写一个跨平台的绝对路径,File类提供了与平台无关的方法来对磁盘上的文件或目录进行操作。
区别是返回值类型不同
class FileTest {
public static void main(String[] args) throws IOException{
//File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
//代表盘符根目录
String strDir = File.separator;
String strFile = "eclipse workplace" + strDir + "FileTest" + strDir + "1.txt";
File f = new File(strDir,strFile);
f.createNewFile();
}
}
删除文件或者目录
f.delete();
在程序退出时删除文件,用于删除程序运行时的文件
deleteOnExit()
创建临时文件并删除临时文件
class FileTest {
public static void main(String[] args) throws IOException, InterruptedException{
File f = File.createTempFile("zfdsfdsd", ".tmp");
f.deleteOnExit();
Thread.sleep(3000);
}
}
列出目录或文件中的所有子文件
class FileTest {
public static void main(String[] args) throws IOException, InterruptedException{
String strDir = File.separator;
//File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
String strAdd = "eclipse workplace" + strDir + "FileTest";
File f = new File(strDir,strAdd);
f.createNewFile();
String[] names = f.list();
for(int i=0;i< names.length;i++){
System.out.println(names[i]);
}
}
}