Java

本类阅读TOP10

·使用MyEclipse开发Struts框架的Hello World!(录像1)
·hibernate配置笔记
·AOP编程入门--Java篇
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·构建Linux下IDE环境--Eclipse篇
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·Tomcat5.5.9的安装配置
·AWT GUI 设计笔记(二)

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
java文件对象操作

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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

 




相关文章

相关软件