Solved

File Handling : Urgent

Posted on 2002-07-19
5
199 Views
Last Modified: 2010-05-19
Hi

I am writing one batch program in java
when it is exceuted it will pick up one CSV file to read.
wht i want is , Before it starts reading the file , i should rename the file so that other instance of the same batch program should not get the same file to read. After reading the file i want to rename the file back to its orignal name.

Thanks and Regards
Harish
0
Comment
Question by:harish_tyagi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
5 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
ID: 7164398
Here's an adaption of the durable FileCopy class by David Flanagan. You can just call rename() in your program, giving it a prefix, such as rename("myfile.csv","_")

import java.io.*;

/**
 * This class is a standalone program to copy a file, and also defines a
 * static copy() method that other programs can use to copy files.
 **/
public class FileCopy {
  /** The main() method of the standalone program.  Calls copy(). */
  public static void main(String[] args) {
    if (args.length != 2)    // Check arguments
      System.err.println("Usage: java FileCopy <source file> <prefix>");
    else {
    // Call rename() to do the copy, and display any error messages it throws.
      rename(args[0],args[1]);
    }
  }

  public static void rename(String filename,String prefix){
     // Call copy() to do the copy, and display any error messages it throws.
    try {
      String newName = prefix + filename ;
      copy(filename,newName);
    }
    catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }

  /**
   * The static method that actually performs the file copy.
   * Before copying the file, however, it performs a lot of tests to make
   * sure everything is as it should be.
   */
  public static void copy(String from_name, String to_name) throws IOException{
    File from_file = new File(from_name);  // Get File objects from Strings
    File to_file = new File(to_name);

    // First make sure the source file exists, is a file, and is readable.
    if (!from_file.exists())
      abort("FileCopy: no such source file: " + from_name);
    if (!from_file.isFile())
      abort("FileCopy: can't copy directory: " + from_name);
    if (!from_file.canRead())
      abort("FileCopy: source file is unreadable: " + from_name);

    // If the destination is a directory, use the source file name
    // as the destination file name
    if (to_file.isDirectory())
      to_file = new File(to_file, from_file.getName());

    // If the destination exists, make sure it is a writeable file
    // and ask before overwriting it.  If the destination doesn't
    // exist, make sure the directory exists and is writeable.
    if (to_file.exists()) {
      if (!to_file.canWrite())
        abort("FileCopy: destination file is unwriteable: " + to_name);
      // Ask whether to overwrite it
      System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
      System.out.flush();
      // Get the user's response.
      BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
      String response = in.readLine();
      // Check the response.  If not a Yes, abort the copy.
      if (!response.equals("Y") && !response.equals("y"))
        abort("FileCopy: existing file was not overwritten.");
    }
    else {
      // if file doesn't exist, check if directory exists and is writeable.
      // If getParent() returns null, then the directory is the current dir.
      // so look up the user.dir system property to find out what that is.
      String parent = to_file.getParent();  // Get the destination directory
      if (parent == null) parent = System.getProperty("user.dir"); // or CWD
      File dir = new File(parent);          // Convert it to a file.
      if (!dir.exists())
        abort("FileCopy: destination directory doesn't exist: " + parent);
      if (dir.isFile())
        abort("FileCopy: destination is not a directory: " + parent);
      if (!dir.canWrite())
        abort("FileCopy: destination directory is unwriteable: " + parent);
    }

    // If we've gotten this far, then everything is okay.
    // So we copy the file, a buffer of bytes at a time.
    FileInputStream from = null;  // Stream to read from source
    FileOutputStream to = null;   // Stream to write to destination
    try {
      from = new FileInputStream(from_file);  // Create input stream
      to = new FileOutputStream(to_file);     // Create output stream
      byte[] buffer = new byte[4096];         // A buffer to hold file contents
      int bytes_read;                         // How many bytes in buffer
      // Read a chunk of bytes into the buffer, then write them out,
      // looping until we reach the end of the file (when read() returns -1).
      // Note the combination of assignment and comparison in this while
      // loop.  This is a common I/O programming idiom.
      while((bytes_read = from.read(buffer)) != -1) // Read bytes until EOF
        to.write(buffer, 0, bytes_read);            //   write bytes
    }
    // Always close the streams, even if exceptions were thrown
    finally {
      if (from != null) try { from.close(); } catch (IOException e) { ; }
      if (to != null) try { to.close(); } catch (IOException e) { ; }
    }
  }

  /** A convenience method to throw an exception */
  private static void abort(String msg) throws IOException {
    throw new IOException(msg);
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 7164408
Actually, I think it might be better to keep the original version of Flanagan's FileCopy, so here's a test class to show how you'd call it, followed by the original:

import java.io.*;

public class TestFileCopy {

  public static void main(String[] args){
    try {
      String fileName = "myfile.csv";
      String prefix = "_";
      String newName = prefix + fileName;
      FileCopy.copy(fileName,newName);
      /*
      do your stuff
      */
      File f = new File(newName);
      System.out.println(f.length());
      f.delete();
    }
    catch(IOException e){
      e.printStackTrace();
    }
  }

}


----------------------------------------------------------

// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import java.io.*;

/**
 * This class is a standalone program to copy a file, and also defines a
 * static copy() method that other programs can use to copy files.
 **/
public class FileCopy {
  /** The main() method of the standalone program.  Calls copy(). */
  public static void main(String[] args) {
    if (args.length != 2)    // Check arguments
      System.err.println("Usage: java FileCopy <source file> <destination>");
    else {
      // Call copy() to do the copy, and display any error messages it throws.
      try { copy(args[0], args[1]); }
      catch (IOException e) { System.err.println(e.getMessage()); }
    }
  }

  /**
   * The static method that actually performs the file copy.
   * Before copying the file, however, it performs a lot of tests to make
   * sure everything is as it should be.
   */
  public static void copy(String from_name, String to_name) throws IOException{
    File from_file = new File(from_name);  // Get File objects from Strings
    File to_file = new File(to_name);
   
    // First make sure the source file exists, is a file, and is readable.
    if (!from_file.exists())
      abort("FileCopy: no such source file: " + from_name);
    if (!from_file.isFile())
      abort("FileCopy: can't copy directory: " + from_name);
    if (!from_file.canRead())
      abort("FileCopy: source file is unreadable: " + from_name);
   
    // If the destination is a directory, use the source file name
    // as the destination file name
    if (to_file.isDirectory())
      to_file = new File(to_file, from_file.getName());
   
    // If the destination exists, make sure it is a writeable file
    // and ask before overwriting it.  If the destination doesn't
    // exist, make sure the directory exists and is writeable.
    if (to_file.exists()) {
      if (!to_file.canWrite())
        abort("FileCopy: destination file is unwriteable: " + to_name);
      // Ask whether to overwrite it
      System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
      System.out.flush();
      // Get the user's response.
      BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
      String response = in.readLine();
      // Check the response.  If not a Yes, abort the copy.
      if (!response.equals("Y") && !response.equals("y"))
        abort("FileCopy: existing file was not overwritten.");
    }
    else {  
      // if file doesn't exist, check if directory exists and is writeable.
      // If getParent() returns null, then the directory is the current dir.
      // so look up the user.dir system property to find out what that is.
      String parent = to_file.getParent();  // Get the destination directory
      if (parent == null) parent = System.getProperty("user.dir"); // or CWD
      File dir = new File(parent);          // Convert it to a file.
      if (!dir.exists())
        abort("FileCopy: destination directory doesn't exist: " + parent);
      if (dir.isFile())
        abort("FileCopy: destination is not a directory: " + parent);
      if (!dir.canWrite())
        abort("FileCopy: destination directory is unwriteable: " + parent);
    }
   
    // If we've gotten this far, then everything is okay.
    // So we copy the file, a buffer of bytes at a time.
    FileInputStream from = null;  // Stream to read from source
    FileOutputStream to = null;   // Stream to write to destination
    try {
      from = new FileInputStream(from_file);  // Create input stream
      to = new FileOutputStream(to_file);     // Create output stream
      byte[] buffer = new byte[4096];         // A buffer to hold file contents
      int bytes_read;                         // How many bytes in buffer
      // Read a chunk of bytes into the buffer, then write them out,
      // looping until we reach the end of the file (when read() returns -1).
      // Note the combination of assignment and comparison in this while
      // loop.  This is a common I/O programming idiom.
      while((bytes_read = from.read(buffer)) != -1) // Read bytes until EOF
        to.write(buffer, 0, bytes_read);            //   write bytes
    }
    // Always close the streams, even if exceptions were thrown
    finally {
      if (from != null) try { from.close(); } catch (IOException e) { ; }
      if (to != null) try { to.close(); } catch (IOException e) { ; }
    }
  }

  /** A convenience method to throw an exception */
  private static void abort(String msg) throws IOException {
    throw new IOException(msg);
  }
}
0
 
LVL 92

Assisted Solution

by:objects
objects earned 50 total points
ID: 7164467
Sounds like you just need to rename the file:

File original = ...;
File newname = ...;
original.renameTo(newname);
0
 
LVL 35

Expert Comment

by:girionis
ID: 8951553
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- split points between CEHJ and objects

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question