您的位置:首页 > 编程语言 > Java开发

java文件对象操作

2004-05-17 23:01 507 查看
在我们进行文件操作时,需要知道一些关于文件的信息。File类提供了一些成员函数 来操纵文件和获得一些文件的信息。

1、创建一个新的文件对象

你可用下面三个方法来创建一个新文件对象:

File myFile; myFile = new File("etc/motd");



myFile = new File("/etc","motd"); //more useful if the directory or filename are variables



File myDir = new file("/etc"); myFile = new File(myDir,"motd");

这三种方法取决于你访问文件的方式。例如,如果你在应用程序里只用一个文件,第一种创建文件的结构是最容易的。但如果你在同一目录里打开数个文件,则第二种或 第三种结构更好一些。

2、文件测试和使用

一旦你创建了一个文件对象,你便可以使用以下成员函数来获得文件相关信息:

文件名 : String getName()
路径: String getPath()
String getAbslutePath()
String getParent()
boolean renameTo(File newName)

文 件 测 试 :

boolean exists() ,

boolean canWrite() ,

boolean canRead() ,

boolean isFile() ,

boolean isDirectory() ,

boolean isAbsolute() 。

一般文件信息 long lastModified() long length()

目录用法 boolean mkdir() String[] list()

3、文件信息获取例子程序

这里是一个独立的显示文件的基本信息的程序,文件通过命令行参数传输:

import java.io.*; class fileInfo{
File fileToCheck;
public static void main(String args[]) throws IOException{
if (args.length>0){
for (int i=0;i<args.length;i++){
fileToCheck = new File(args[i]);
info(fileToCheck);
}
}
else
{
System.out.println("No file given.");
}
}

public void info (File f) throws IOException {
System.out.println("Name: "+f.getName());
System.out.println("Path: "=f.getPath());
if (f.exists()) {
System.out.println("File exists.");
System.out.print((f.canRead() ?" and is Readable":"")); System.out.print((f.cnaWrite()?" and is Writeable":"")); System.out.println("."); System.out.println("File is " + f.lenght() = " bytes."); } else { System.out.println("File does not exist."); } } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: