1.File类的文件的创建与删除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package
com.lixiyu;
import
java.io.File;
//导入java.io.File类
public
class
FileTest {
//创建类FileTest
public
static
void
main(String[] args){
//主方法
File file=
new
File(
"D:/"
,
"test.txt"
);
//创建文件对象
if
(file.exists()){
//如果文件已经存在
file.delete();
//将文件删除
System.out.println(
"文件已删除"
);
//输出提示信息
}
else
{
//如果文件不存在
try
{
//try语句块捕捉可能出现的异常
file.createNewFile();
//创建该文件
System.out.println(
"文件已创建"
);
//输出的提示信息
}
catch
(Exception e){
//catch处理该异常
e.printStackTrace();
//输出异常信息
}
}
}
}
|
2.获取文件信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package
com.lixiyu;
import
java.io.File;
public
class
FileTest1 {
public
static
void
main(String[] args){
File file=
new
File(
"D:/"
,
"test.txt"
);
if
(file.exists()){
String name=file.getName();
long
length=file.length();
boolean
hidden=file.isHidden();
System.out.println(
"文件名称:"
+name);
System.out.println(
"文件长度:"
+length);
System.out.println(
"该文件是否隐藏:"
+hidden);
}
else
{
System.out.println(
"该文件不存在"
);
}
}
}
|
本文转自lixiyu 51CTO博客,原文链接:http://blog.51cto.com/lixiyu/1308105,如需转载请自行联系原作者