java文件对象操作

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

在我们进行文件操作时,需要知道一些关于文件的信息。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."); } } }

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航