Java Tutorial/File/File

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

canRead(): Returns true if you are permitted to read the file and false otherwise.

This method can throw a SecurityException if the file is not permitted.



import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.canRead());
  }
}



false


canWrite(): Returns true if you are permitted to write to the file and false otherwise.

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.canWrite());
  }
}





Change a file attribute to read only

import java.io.File;
public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("ReadOnly.txt");
    file.createNewFile();
    file.setReadOnly();
    if (file.canWrite()) {
      System.out.println("writable!");
    } else {
      System.out.println("read only!");
    }
  }
}





Change a file attribute to writable

import java.io.File;
public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("Writable.txt");
    file.createNewFile();
    file.setReadOnly();
    if (file.canWrite()) {
      System.out.println("File is writable!");
    } else {
      System.out.println("File is in read only mode!");
    }
    file.setWritable(true);
    if (file.canWrite()) {
      System.out.println("File is writable!");
    } else {
      System.out.println("File is in read only mode!");
    }
  }
}





Create a file and change its attribute to readonly

import java.io.File;
import java.io.IOException;
public class FileAttributesDemo {
  public static void main(String[] args) throws IOException {
    // Create a new file, by default canWrite=true, readonly=false
    File file = new File("test.txt");
    if (file.exists()) {
      file.delete();
    }
    file.createNewFile();
    System.out.println("Before. canWrite?" + file.canWrite());
    // set to read-only, atau canWrite = false */
    file.setWritable(false);
    System.out.println("After. canWrite?" + file.canWrite());
  }
}





Create a human-readable file size

import org.apache.rumons.io.FileUtils;
import java.io.File;
public class Main {
  public static void main(String[] args) {
    File file = new File("c:\\java.exe");
    long size = file.length();
    String display = FileUtils.byteCountToDisplaySize(size);
    System.out.println("Name    = " + file.getName());
    System.out.println("size    = " + size);
    System.out.println("Display = " + display);
  }
}





createNewFile(): Creates a new empty file

import java.io.File;
public class MainClass {
  public static void main(String[] a)throws Exception {
    File file = new File("c:\\test\\test.txt");
    file.createNewFile();
  }
}





Creates a file and sets it to read-only.

import java.io.File;
import java.io.IOException;
public class FileAttributesDemo {
    public static void main (String[] args) throws IOException {
        // Create a new file, by default canWrite=true,
       readonly=false
        File file = new File ("test.txt");
        if (file.exists ()) {
            file.delete ();
        }
        file.createNewFile ();
        System.out.println ("Before. canWrite?" + file.canWrite ());
        // set to read-only, atau canWrite = false */
        file.setWritable (false);
        System.out.println ("After. canWrite?" + file.canWrite ());
    }
}





createTempFile(String prefix, String suffix, File directory): a static method that creates a temporary file

import java.io.File;
public class MainClass {
  public static void main(String[] a) throws Exception {
    File tmp = File.createTempFile("foo", "tmp");
    System.out.println("Your temp file is " + tmp.getCanonicalPath());
  }
}





delete(): delete the file or directory

won"t delete directories that are not empty.



import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\test\\test.txt");
    boolean success = file.delete();
    System.out.println(success);
  }
}





deleteOnExit(): delete file or directory when the program ends

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\test\\test.txt");
    file.deleteOnExit();
  }
}





Display File class constants and test some methods

import java.io.File;
class FileDemo {
  public static void main(String args[]) throws Exception {
    // Display constants
    System.out.println("pathSeparatorChar = " + File.pathSeparatorChar);
    System.out.println("separatorChar = " + File.separatorChar);
    // Test some methods
    File file = new File(args[0]);
    System.out.println("getName() = " + file.getName());
    System.out.println("getParent() = " + file.getParent());
    System.out.println("getAbsolutePath() = " + file.getAbsolutePath());
    System.out.println("getCanonicalPath() = " + file.getCanonicalPath());
    System.out.println("getPath() = " + file.getPath());
    System.out.println("canRead() = " + file.canRead());
    System.out.println("canWrite() = " + file.canWrite());
  }
}





exists(): Returns true if it exists and false otherwise

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.exists());
  }
}



false


File Class Enhancements

The java.io.File class in Mustang comes with several new features.

The java.io.File class in Mustang provides methods for checking hard disk space and the amount used.

The java.io.File class in Mustang possesses methods for changing file attributes.

Here are the new methods:



public long getFreeSpace ()   Returns the size, in bytes, of the partition referenced by this File object.
public long getFreeSpace ()   Returns the amount of free space, in bytes, in the partition referenced by this File object.
public long getUsableSpace ()   Returns the number of bytes available to this virtual machine on the partition referenced by this File object. The difference between getUsableSpace and getFreeSpace is that the former takes into account restrictions imposed by the operating system, such as write permissions. The latter does not.
public boolean setWritable (boolean writable, boolean ownerOnly)   Sets the owner"s or everybody"s write permission for the path referenced by this File object.
public boolean setWritable (boolean writable)   Sets the owner"s write permission for the path referenced by this File object.
public boolean setReadable (boolean readable, boolean ownerOnly)    Sets the owner"s or everybody"s read permission for the path referenced by this File object.
public boolean setReadable (boolean readable)    Sets the owner"s read permission for the path referenced by this File object.
public boolean setExecutable (boolean executable, boolean ownerOnly)    Sets the owner"s or everybody"s execute permission for the path referenced by this File object.
public boolean setExecutable (boolean executable)   Sets the owner"s execute permission for the path referenced by this File object.
public boolean canExecute ()    Tests if the application has the right to execute the file referenced by this File object.



Total space on C: = 40015953920bytes
Free space on C: = 6470483968bytes


File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.

import java.io.File;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file1 = new File("./filename");
    File file2 = new File("filename");
    System.out.println(file1.equals(file2));
    file1 = file1.getCanonicalFile();
    file2 = file2.getCanonicalFile();
    System.out.println(file1.equals(file2));
  }
}





Filtering a File List

import java.io.File;
import java.io.FilenameFilter;
import java.util.Date;
class FileListFilter implements FilenameFilter {
  private String name;
  private String extension;
  public FileListFilter(String name, String extension) {
    this.name = name;
    this.extension = extension;
  }
  public boolean accept(File directory, String filename) {
    boolean fileOK = true;
    if (name != null) {
      fileOK = filename.startsWith(name);
    }
    if (extension != null) {
      fileOK = filename.endsWith("." + extension);
    }
    return fileOK;
  }
}
public class MainClass {
  public static void main(String[] args) {
    File myDir = new File("C:/");
    FilenameFilter select = new FileListFilter("F", "txt");
    File[] contents = myDir.listFiles(select);
    for (File file : contents) {
      System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file")
          + " last modified on\n" + new Date(file.lastModified()));
    }
  }
}





getAbsoluteFile(): Returns a File object containing the absolute path for the directory or file referenced by the current File object.

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getAbsoluteFile());
  }
}



C:\jdk1.5.0\File.java


getAbsolutePath(): Returns the absolute path for the directory or file referenced by the current File object

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getAbsolutePath());
  }
}



C:\jdk1.5.0\File.java


Get all xml files by file extension

import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] argv) {
    getXMLFiles(new File("c:\\a"));
  }
  public static File[] getXMLFiles(File folder) {
    List<File> aList = new ArrayList<File>();
    File[] files = folder.listFiles();
    for (File pf : files) {
      if (pf.isFile() && getFileExtensionName(pf).indexOf("xml") != -1) {
        aList.add(pf);
      }
    }
    return aList.toArray(new File[aList.size()]);
  }
  public static String getFileExtensionName(File f) {
    if (f.getName().indexOf(".") == -1) {
      return "";
    } else {
      return f.getName().substring(f.getName().length() - 3, f.getName().length());
    }
  }
}





Get file extension name

import java.io.File;
public class Main {
  public static void main(String[] argv) {
    getFileExtensionName(new File("a.txt"));
  }
  public static String getFileExtensionName(File f) {
    if (f.getName().indexOf(".") == -1) {
      return "";
    } else {
      return f.getName().substring(f.getName().length() - 3, f.getName().length());
    }
  }
}





Get icon for file type

import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File(args[0]);
    sun.awt.shell.ShellFolder sf = sun.awt.shell.ShellFolder.getShellFolder(file);
    Icon icon = new ImageIcon(sf.getIcon(true));
    System.out.println("type = " + sf.getFolderType());
    JLabel label = new JLabel(icon);
    JFrame frame = new JFrame();
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }
}





getParentFile(): Returns the parent directory as a File object, or null if this File object does not have a parent.

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getParentFile());
    System.out.println(myFile);
  }
}



C:\jdk1.5.0
C:\jdk1.5.0\File.java


getParent(): Returns the name of the parent directory of the file or directory represented

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getParent());
    System.out.println(myFile);
  }
}



C:\jdk1.5.0
C:\jdk1.5.0\File.java


Get the free space

import java.io.File;
public class SpaceChecker {
  public static void main(String[] args) {
    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
      System.out.println(roots[i]);
      System.out.println("Free space = " + roots[i].getFreeSpace());
      System.out.println();
    }
  }
}





Get the total space

import java.io.File;
public class SpaceChecker {
  public static void main(String[] args) {
    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
      System.out.println(roots[i]);
      System.out.println("Total space = " + roots[i].getTotalSpace());
      System.out.println();
    }
  }
}





Get the usable space

import java.io.File;
public class SpaceChecker {
  public static void main(String[] args) {
    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
      System.out.println(roots[i]);
      System.out.println("Usable space = " + roots[i].getUsableSpace());
      System.out.println();
    }
  }
}





Getting a Proper URL from a File Object

import java.io.*;
import java.net.*;
public class FileURL {
  public static void main(String args[]) throws MalformedURLException {
    File file = new File("The End");
    URL url2 = file.toURI().toURL();
    System.out.printf("Good url %s%n", url2);
  }
}





isAbsolute(): Returns true if the File object refers to an absolute pathname, and false otherwise.

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.isAbsolute());
  }
}





isDirectory(): Returns true if it is an existing directory and false otherwise

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.isDirectory());
  }
}



false


isFile(): Returns true if it is an existing file and false otherwise

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.isFile());
  }
}



false


isHidden(): Returns true if it is hidden and false otherwise

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.isHidden());
  }
}





lastModified(): Returns last modified time in milliseconds since midnight on 1st January MT

import java.io.File;
import java.util.Date;
public class MainClass {
  public static void main(String[] args) {
    // Create an object that is a directory
    File myDir = new File("C:/Java_Dev");
    System.out.println(new Date(myDir.lastModified()));
  }
}



Wed Nov 01 13:59:20 PST 2006


length(): Returns the length of current file in long

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator);
    System.out.println(myFile.length());
  }
}





List all roots

import java.io.File;
public class SpaceChecker {
  public static void main(String[] args) {
    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
      System.out.println(roots[i]);
      System.out.println("Free space = " + roots[i].getFreeSpace());
      System.out.println("Usable space = " + roots[i].getUsableSpace());
      System.out.println("Total space = " + roots[i].getTotalSpace());
      System.out.println();
    }
  }
}





listFiles(): Returns a File array containing the children files and directories

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator);
    for(File s: myFile.listFiles()){
      System.out.println(s);
    }
  }
}



C:\WINDOWS
C:\winscp.RND
C:\WinXPprep
C:\WUTemp
...


list(): Returns a string array containing the children files and directories

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator);
    for(String s: myFile.list()){
      System.out.println(s);
    }
  }
}



System.FormatException
admin.lnk
admiss.lnk
AUTOEXEC.BAT
bea
boot.ini
CONFIG.SYS
Documents and Settings
getadmiss.ftp
...


mkdir(): Creates a directory

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\test\\");
    file.mkdir();
  }
}





mkdirs(): Creates a directory including any parent directories

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\test\\test\\");
    file.mkdirs();
  }
}





Providing a URI for a remote file

import java.io.File;
import java.net.URI;
public class MainClass {
  public static void main(String[] a) throws Exception {
    File remoteFile = new File(new URI("file:///index.htm"));
  }
}





renameTo(File path): Rename a file or directory

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\text.txt");
    file.renameTo(new File("c:\\text.txt.bak"));
  }
}





Set file attributes.

import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    File f = new File("name.txt");
    if (!f.exists()) {
      System.out.println("File not found.");
      return;
    }
    if (f.canRead())
      System.out.println("  Readable");
    else
      System.out.println("  Not Readable");
    if (f.canWrite())
      System.out.println("  Writable");
    else
      System.out.println("  Not Writable");
    System.out.println("  Last modified on " + new Date(f.lastModified()));
    long t = Calendar.getInstance().getTimeInMillis();
    if (!f.setLastModified(t))
      System.out.println("Can"t set time.");
    if (!f.setReadOnly())
      System.out.println("Can"t set to read-only.");
    if (f.canRead())
      System.out.println("  Readable");
    else
      System.out.println("  Not Readable");
    if (f.canWrite())
      System.out.println("  Writable");
    else
      System.out.println("  Not Writable");
    System.out.println("  Last modified on " + new Date(f.lastModified()));
    if (!f.setWritable(true, false))
      System.out.println("Can"t return to read/write.");
    if (f.canRead())
      System.out.println("  Readable");
    else
      System.out.println("  Not Readable");
    if (f.canWrite())
      System.out.println("  Writable");
    else
      System.out.println("  Not Writable");
  }
}





setReadOnly(): Sets the file as read-only and returns true if the operation is successful

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\text.txt");
    file.setReadOnly();
    System.out.println(file.canRead());
  }
}





Testing and Checking File Objects: file name and path

getName(): Returns the name of the file without the path or the directory name



import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getName());
    System.out.println(myFile.getPath());
  }
}



File.java
C:\jdk1.5.0\File.java


The File Class

A File object represents a file or directory pathname. You can pass an absolute path to a file or directory like this:



File file1 = new File ("C:\\temp\\myNote.txt"); // in Windows
File file2 = new File ("/tmp/myNote.txt"); // in Linux/Unix





toString(): Returns a String representation of the current File object

The string that is returned is the same as that returned by the getPath() method.



import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getParentFile());
    System.out.println(myFile);
  }
}