1.创建一个新文件
方法:public boolean createNewFile()
需求:在E盘创建一个test.txt文件
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File file = new File("E:\\test.txt");//实例化File类对象
boolean i =file.createNewFile();//创建文件,根据给定的路径创建
System.out.println(i);
}
}
</span>
特殊声明:
开发时要注意路径问题:
windows中使用反斜杠:“\”
linux中使用正斜杠:“/”
如果要让Java程序的可移植性保持,则最好根据所在的操作系统来自动使用分隔符;。
补充知识(调用静态常量):
File.pathSeparator——“;”
File.separator——“\”
完善后代码:
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator + "test.txt"); // 实例化File类的对象
try {
f.createNewFile(); // 创建文件,根据给定的路径创建
} catch (IOException e) {
e.printStackTrace(); // 输出异常信息
}
}
}
</span>
2.删除一个指定的文件
方法:public boolean delete();
public boolean exists(); 用来判断一个文件是否存在
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File f = new File("E:" + File.separator + "test.txt");// 实例化File类的对象
if (f.exists()) {// 如果文件存在,则删除
f.delete();// 删除文件
}
}
}
</span>
3.创建一个文件夹
方法:public boolean mkdir()
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File f = new File("E:" + File.separator + "test");// 实例化File类的对象
f.mkdir();//创建文件夹
}
}
</span>
4.列出指定目标的全部内容
方式一:使用list()列出全部内容
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator); // 实例化File类的对象
String str[] = f.list(); // 列出给定目录中的内容
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
</span>
注:以上只是列出了全部的名字,包括文件夹的名字、文件的名字。
方式二:使用listFiles()列出
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator); // 实例化File类的对象
File files[] = f.listFiles(); // 列出全部内容
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
}
}
</span>
注:列出的是一个完整的路径,这样对于程序本身来说是很容易进行其他操作的。
5.判断一个给定的路径是否是目录
方法:public boolean isDirectory()
<span style="font-size:14px;">public class Test {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test"); // 实例化File类的对象
if (f.isDirectory()) { // 判断是否是目录
System.out.println(f.getPath() + "路径是目录。");
} else {
System.out.println(f.getPath() + "路径不是目录。");
}
}
}
</span>
6.列出指定内容的全部内容
<span style="font-size:14px;">/*
* 遍历指定目录下的文件
*/
public class Test {
public static void main(String[] args) throws IOException {
File file = new File("E:\\test");
fileDir(file);
}
private static void fileDir(File dir) {
File[] files = dir.listFiles();//获得表示目录下所有文件的数组
for(File file:files){//遍历所有的子目录和文件
if(file.isDirectory()){
fileDir(file);//如果有目录,则递归调用
}
System.out.println(file.getAbsolutePath());//输出文件的绝对路径
}
}
}
</span>