发表于: java/j2ee | 作者: | 日期: 2008/12/20 03:12

Java IO概述
IO是input、ouput的缩写,指应用程序与外部设备间的输入与输出。与应用程序交互最频繁的外部设备就是磁盘,java中有专门的io包管理磁盘的操作。包java.io通过如下类完成对磁盘操作的管理:File、FileDescriptor 、FileInputStream、FileOutputStream、RamdomAccessFile以及接口 FilenameFilter。

File类的使用
类 File 提供了一种与机器无关的方式来描述一个文件对象的属性。通过类File所提供的方法,可以得到文件的描述信息,包括名称、所在路径、可读性、可写性、长度等,还可以对文件进行各种操作:生成新文件、改变文件名、删除文件等。

对于目录,Java把它简单地处理为一种特殊的文件,即文件名的列表,也用File类进行表示。通过File类提供的方法,可以对目录进行创建、遍历等操作。

java对路径分隔符的要求相当宽松,以下格式的路径表示java都能够正确识别并定位到同一个文件:


File f1 = new File(“d:\\1.txt”);
File f3 = new File(“d:/2.txt”);
File f2 = new File(“d://3.txt”);

示例代码:

/* 创建文件 */

public static void createFile() {
try {
File f1 = new File(“d:\\1.txt”);
File f2 = new File(“d:/2.txt”);
File f3 = new File(“d://3.txt”);
f1.createNewFile();
f2.createNewFile();
f3.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}

/* 删除文件 */

public static void delFile() {
try {
File f1 = new File(“d:\\1.txt”);
File f2 = new File(“d:/2.txt”);
File f3 = new File(“d://3.txt”);
if (f1.exists()) {
f1.delete();
}
if (f2.exists()) {
f2.delete();
}
if (f3.exists()) {
f3.delete();
}

} catch (Exception e) {
e.printStackTrace();
}
}

/* 创建目录 */

public static void createFolder() {
try {
File f1 = new File(“d:\\folder1”);
File f2 = new File(“d:/folder2”);
File f3 = new File(“d://folder3”);
f1.mkdir();
f2.mkdir();
f3.mkdir();
} catch (Exception e) {
e.printStackTrace();
}

}

/* 删除目录 */

public static void delFolder() {
try {
File f1 = new File(“d:\\folder1”);
File f2 = new File(“d:/folder2”);
File f3 = new File(“d://folder3”);
if (f1.exists()) {
f1.delete();
}
if (f2.exists()) {
f2.delete();
}
if (f3.exists()) {
f3.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}

/* 获得文件属性 */

public static void getFileProperies() {
try {
File f1 = new File(“d:\\1.txt”);
if (!f1.exists()) {
f1.createNewFile();
}
f1.setReadOnly();

if (f1.isFile()) {
System.out.println(“f1.txt是文件”);
} else if (f1.isDirectory()) {
System.out.println(“f1.txt是目录”);
}

if (f1.canRead()) {
System.out.println(“f1.txt可读取”);
} else {
System.out.println(“f1.txt不可读取”);
}

if (f1.canWrite()) {
System.out.println(“f1.txt可写入”);
} else {
System.out.println(“f1.txt不可写入”);
}
if (f1.isHidden()) {
System.out.println(“f1.txt是隐藏文件”);
} else {
System.out.println(“f1.txt不是隐藏文件”);
}

} catch (Exception e) {
e.printStackTrace();
}
}

File类的方法基本上都是见名知义的,但有几点需要注意:

1:如果目录不为空则该目录不能通过File.delete()方法删除;
2:File类的方法只能对文件本身属性进行操作,而不能对文件内容进行操作。

: https://blog.darkmi.com/2008/12/20/726.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.