Java file

Java file Print E-mail
Written by Administrator   
Friday, 14 July 2006

Java file overview

Java File class is represented of  file and directory pathnames. A pathname has two components:

  • An optional system-dependent prefix string,
    such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
  • A sequence of zero or more string names.

Creating Java File Objects

There have three constructors for creating File objects. The simplest accepts a String object as an argument that specifies a path for a file or a directory. For example,

File myfile = new File("C:/temp/tempfile");

You can also create a File object that represents a pathname for a file by using a constructor that allows you to specify the directory that contains the file and the file name separately.

For example,

File tempDir = new File("C:/temp");  // Parent directory
File tempFile = new File(tempDir, "Hwllo.java");         // The path to the file

The fourth constructor allows you to define a File object from an object of type URI that encapsulates a Uniform Resource Identifier

For example,

 File remoteFile = new File(new URL(http://www.devx.biz/java));

Absolute and Relative Paths

In general, the pathname that you use to create a File object has two parts: an optional prefix, followed by a series of names separated by the system default separator character for pathnames. Under MS Windows the prefix for a path on a local drive will be a string defining the drive, such as "C:\\" or "C:/". Under Unix the prefix will be a forward slash, "/". A path that includes a prefix is an absolute path and since it includes a prefix it is not system-independent. A path without a prefix is a relative path and as long as it consists of one or more names separated by characters specified as File.separator or File.separatorChar it should be portable across different systems.

On a computer with the name myLT, with a shared directory shared, you could create a File object as follows:

File myFile = new File("\\\\myLT\\shared\\temp\\src\\java\\io",
                         "Hello.java");

Relative Paths

File myFile = new File(File.separator + File.separator + "myLT" +
                       File.separator + "shared" + File.separator +
                       "temp", "Hello.java");

Deleting a File

    boolean success = (new File("filename")).delete();
    if (!success) {
        // Deletion failed
    }

Copying Java Files

 Using file streams to copy the contents of one file to another file. 


    void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

Using file channel

A file channel defines two methods

transferTo(long position, long count, WritableByteChannel dst)

Attempts to transfer count bytes from this channel to the channel, dst. Bytes are read from this channel starting at the file position specified by position. The position of this channel is not altered by this operation but the position of dst will be incremented by the number of bytes written. Fewer than count bytes will be transferred if this channel's file has fewer than count bytes remaining, or if dst is non-blocking and has fewer than count bytes free in its system output buffer. The number of bytes transferred is returned as type int.

transferFrom(ReadableByteChannel src, long position, long count)

Attempts to transfer count bytes to this channel from the channel src. Bytes are written to this channel starting at the file position specified by position. The position of this channel is not altered by the operation but the position of src will be incremented by the number of bytes read from it. If position is greater than the size of the file, then no bytes will be transferred. Fewer than count bytes will be transferred if the file corresponding to src has fewer than count bytes remaining in the file or if it is non-blocking and has fewer than count bytes free in its system input buffer. The number of bytes transferred is returned as type int.

Example

import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;

public class FileCopy {
  public static void main(String[] args) {
    if(args.length==0) {
      System.out.println("No file to copy. Application usage is:\n"+
                         "java -classpath . FileCopy \"filepath\"" );
      System.exit(1);
    }
    File fromFile = new File(args[0]);

    if(!fromFile.exists()) {
      System.out.println("File to copy, "+fromFile.getAbsolutePath()
                       + ", does not exist.");
      System.exit(1);
    }
   
    File toFile = createBackupFile(fromFile);
    FileInputStream inFile = null;
    FileOutputStream outFile = null;
    try {
      inFile = new FileInputStream(fromFile);
      outFile = new FileOutputStream(toFile);

    } catch(FileNotFoundException e) {
      e.printStackTrace(System.err);
      assert false;
    }

    FileChannel inChannel = inFile.getChannel();   
    FileChannel outChannel = outFile.getChannel();

    try {
      int bytesWritten = 0;
      long byteCount = inChannel.size();
      while(bytesWritten<byteCount)
        bytesWritten += inChannel.transferTo(bytesWritten,
                                             byteCount-bytesWritten,
                                             outChannel);
     
      System.out.println("File copy complete. " + byteCount
                       + " bytes copied to "
                       + toFile.getAbsolutePath());
      inFile.close();
      outFile.close();

    } catch(IOException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    System.exit(0);
  }

 }

Questions about java file

Which gets the name of the parent directory file “file.txt”?

A. String name= File.getParentName(“file.txt”);
B. String name= (new File(“file.txt”)).getParent();
C. String name = (new File(“file.txt”)).getParentName();
D. String name= (new File(“file.txt”)).getParentFile();
E. Directory dir=(new File (“file.txt”)).getParentDir(); String name= dir.getName();

What writes the text “<end>” to the end of the file “file.txt”?

A. OutputStream out= new FileOutputStream (“file.txt”);
                     Out.writeBytes (“<end>/n”);
B. OutputStream os= new FileOutputStream (“file.txt”, true); DataOutputStream out = new DataOutputStream(os); out.writeBytes (“<end>/n”);
C. OutputStream os= new FileOutputStream (“file.txt”); DataOutputStream out = new DataOutputStream(os); out.writeBytes (“<end>/n”);
D. OutputStream os= new OutputStream (“file.txt”, true); DataOutputStream out = new DataOutputStream(os); out.writeBytes (“<end>/n”);

Last Updated ( Saturday, 15 July 2006 )

  home              contact us

 

©2006-2010 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground