Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / April 2005

Tip: Looking for answers? Try searching our database.

FileReader/FileWriter question

Thread view: 
Paul Fedorenko - 14 Apr 2005 03:47 GMT
I'm having issues with a file I/O assignment for my Java class.  This
program's supposed to copy the contents of one file (specified in a
command-line argument) into another file (also specified at command-line).
I've created file objects for the program, as well as FileReader and
FileWriter objects, and going on what I know about this stuff, it should
work.

Compiler error says that the line:

       FileWriter fout = new FileWriter(outputFile);

isn't a statement and that there's a ; missing.

Any thoughts would be much appreciated.

File listed below...
___________________________________________________________________________________________
import java.io.*;

public class CopyFilesUsingFileStreams
{
public static void main(String[] args)
{
       // Declare input and output file streams
       File inputFile = new File(args[0]);
       File outputFile = new File(args[1]);

       // Check usage
       if (args.length != 2)
      {
  System.out.println(
    "Usage: java CopyFilesUsingFileStreams fromfile tofile");
  System.exit(0);
 }

 try
 {
  FileReader fin = new FileReader(inputFile);

  File file = new File(args[1]);
  if (file.exists())
  {
   System.out.println("file " + args[1] + " already exists");
   return;
  }

  else
   FileWriter fout = new FileWriter(outputFile);

  // Display the file size
  System.out.println("The file " + args[0] + " has "
    + in.available() + " bytes");

  // Continuously read a byte from from in and write it to out
  int r;
  while ((r = fin.read()) != -1)
  {
   fout.write((byte)r);
  }
 }

 catch (FileNotFoundException ex)
 {
  System.out.println("File not found: " + args[0]);
 }

 catch (IOException ex)
 {
  System.out.println(ex.getMessage());
 }

 finally
 {
  try
  {
   // Close files
   if (fin != null) fin.close();
   if (fout != null) fout.close();
  }

  catch (IOException ex)
  {
   System.out.println(ex);
  }
 }
}
}
klynn47@comcast.net - 14 Apr 2005 05:52 GMT
Well the problem with the way it's setup now is that since it's part of
the else, unless you use braces you can't put a declaration like that
in one line.

Another problem you will have with the way it's set up is that if you
declare fout in the else statement, you won't be able to reference fout
after the else.
John McGrath - 14 Apr 2005 06:19 GMT
> Compiler error says that the line:
>
>         FileWriter fout = new FileWriter(outputFile);
>
> isn't a statement

That's because it is not a statement.  It is a declaration.

If you think about it, it does not make much sense for the else clause of
an if statement to consist of a declaration.  Its scope would be just the
else clause, so the identifier being declared cannot be referred to.

Check the production for "Statement" in the Java Language grammar:

  http://java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html

Signature

Regards,

John McGrath

Paul Fedorenko - 14 Apr 2005 20:15 GMT
> That's because it is not a statement.  It is a declaration.

Ah.  Yes, I see the problem now.

> If you think about it, it does not make much sense for the else clause of
> an if statement to consist of a declaration.  Its scope would be just the
> else clause, so the identifier being declared cannot be referred to.

I was under the impression, for some reason, that the line would create a
file and associated reference object for use later on in the program if a
file by the specified name didn't already exist.
John McGrath - 15 Apr 2005 00:33 GMT
> > If you think about it, it does not make much sense for the else clause
> > of an if statement to consist of a declaration.  Its scope would be
[quoted text clipped - 4 lines]
> a file and associated reference object for use later on in the program
> if a file by the specified name didn't already exist.

I do not understand what this has to do with the text that you quoted.  
I was talking about the Java language and the scope that the declaration
would have had were it legal there.  You seem to be talking about how a
FileWriter works.

Signature

Regards,

John McGrath

Paul Fedorenko - 15 Apr 2005 03:10 GMT
> I do not understand what this has to do with the text that you quoted.
> I was talking about the Java language and the scope that the declaration
> would have had were it legal there.  You seem to be talking about how a
> FileWriter works.

Simple matter of misunderstanding on my part of how file I/O in Java works.
I think I'm well on the way to getting it sorted out.  I'd better be, at any
rate, since the thing's due tomorrow.  <grin>
Paul Fedorenko - 14 Apr 2005 21:33 GMT
On a related note...  How would I do something like:

   if (specified file doesn't exist)
   {
       do stuff;
   }

   else
   {
       System.out.println("file " + args[1] + " already exists");
       return;
   }

Actually, that wouldn't work either.  The program needs to check for the
existance of a file with the specified name.  If the file doesn't exist, a
new file is supposed to be created.  If the file DOES exist, the contents of
the above else block get executed.

To create a new output file, I'm using:  File file = new File(args[1]);
which creats the second file specified at the commandline (the first is
assumed to exist, since that's the one you're copying).

Unfortunately, for the line:  if (file.exists())  to work, the previous
statement needs to be put into the code before the test, and if I do that,
the "file exists" test fails and the program ends because a new file can't
be created because it's already there.

Part of the problem that I'm running into is that for the assignment, I'm
supposed to rewrite a program that uses byte streams so that it uses
FileReader and FileWriter instead.  The problem is that the book
("Introduction to Java Programming" by Y. Daniel Liang), doesn't actually
mention *anywhere* in the chapter in I/O how FileReader and FileWriter are
actually supposed to be used.

The instructor gave us an example of how those two methods are used, and
I've used it pretty much word-for-word in my program, except that I used
args[] instead of specifying file names.
John McGrath - 15 Apr 2005 00:33 GMT
> To create a new output file, I'm using:  File file = new File(args[1]);
> which creats the second file specified at the commandline (the first is
[quoted text clipped - 4 lines]
> that, the "file exists" test fails and the program ends because a new
> file can't be created because it's already there.

Creating a java.io.File object does not create a disk (or whatever) file.
A File object just encapsulates the name and path of a file.

> Part of the problem that I'm running into is that for the assignment,
> I'm supposed to rewrite a program that uses byte streams so that it uses
> FileReader and FileWriter instead.  The problem is that the book
> ("Introduction to Java Programming" by Y. Daniel Liang), doesn't
> actually mention anywhere in the chapter in I/O how FileReader and
> FileWriter are actually supposed to be used.

Check the JavaDocs.

> The instructor gave us an example of how those two methods are used, and
> I've used it pretty much word-for-word in my program, except that I used
> args[] instead of specifying file names.

A stylistic comment:  I think that writing your file copying code using
args[1] as the file name argument is a bad idea.  It would be far more
readable if you separated your command line processing from the code that
copies the file.  One simple approach is to start your main program out
with something like this:

  public static void main( String[] args ) {
     if ( args.length != 2 ) {
        System.err.println( "....." );
        System.exit( 1 );
     }

     String inputFile = args[0];
     String outputFile = args[1];

     // file copying.
  }

Even better, move the file copying code into a separate method.

Signature

Regards,

John McGrath

Paul Fedorenko - 15 Apr 2005 06:42 GMT
Ok.  I got it.  Thanks for the suggestions.  I ended up deleting the code
that I had and starting from scratch with a completely different approach.
It seems to work properly, so I'm handing it in as is.
Dale King - 17 Apr 2005 01:19 GMT
> I'm having issues with a file I/O assignment for my Java class.  This
> program's supposed to copy the contents of one file (specified in a
> command-line argument) into another file (also specified at command-line).
> I've created file objects for the program, as well as FileReader and
> FileWriter objects, and going on what I know about this stuff, it should
> work.

In addition to your problem with the else close, if you are doing a
byte-for-byte copy you should not be using a Reader or Writer. Readers
and Writer are ONLY meant for text. They use a character encoding to
translate between the byte stream to Unicode characters. FileReader and
FileWriter use the default character encoding for the platform it is
running on. This conversion is not necessarily a reversible transform
for all bytes. In particular it is NOT reversible on Windows. If you use
this method for a binary file, the file will likely get mangled.

You should be using FileInputStream and FileOutputStream which are meant
for byte data.

And on another side note, I recommend completely forgetting about the
FileReader and FileWriter classes. They are a bad idea that should have
never been added to Java. All they are are shorthand for the more
explanatory expression:

    new InputStreamReader( new FileInputStream( arg ) )

If you look at the source for the classes they contain nothing but
constructors.
Paul Fedorenko - 18 Apr 2005 04:15 GMT
> In addition to your problem with the else close, if you are doing a
> byte-for-byte copy you should not be using a Reader or Writer. Readers and
> Writer are ONLY meant for text. They use a character encoding to translate
> between the byte stream to Unicode characters. FileReader and

I understand all that, the difference between byte streams and
FileReader/Writer, I mean.  Thanks for the tips in your post, though.  I'll
definitely keep that in mind in the future.  The problem is, the assignment
was basically along the lines of, "Rewrite the program in example 17.2 to
use FileReader and FileWriter."  Example 17.2 used byte streams, so getting
it to use FileReader and FileWriter basically involved a complete rewrite,
but I think I got it working reasonably well.  I get it back tomorrow, in
time for the final exam.  Exciting, eh?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.