dimanche 29 novembre 2015

FileReader/Writer not writing after flush and close because of if statement [duplicate]

This question already has an answer here:

I'm having quite a bit of trouble with my code. The objective is to read an existing file and copy (via FileReader and FileWriter) that text into a new file. The issue I face is that the file is created, but empty. However, it will write the text without the first if statement that checks whether the user has entered an "r". I have not found other questions that tackle this problem with if.

The purpose of the if is to read the third command line argument and determine whether it will write a new file (r = replace) or append (a) to an existing one.

Simply put, with the if, the file is created and contains text. Without the if, file exists but no text.

import java.io.*;

public class Copy2  {
 public static void main(String []args)  {

  if(args.length == 3)  {
     try    {
        FileReader in = new FileReader(args[0]);
        FileWriter out = new FileWriter(args[1]);
        int chr = in.read();    // read the first character

        if(args[2] == "r"){ //This is the if statement that causes trouble
           while(chr != -1) {   // continue reading and writing until end 
              out.write(chr);
              chr = in.read();
           }
           out.flush();
           in.close();
           out.close();
        }   
     } //try
     catch(IOException e)  {
        System.out.println("Exception: " +  e.getMessage());
     }

  }
  else   {
     System.out.println("Please enter correct number of arguments");
  }

 } //main

} //class  

This code is not complete, I know there is more I need to add, however this phenomenon has me quite puzzled. Any ideas where my problem lies?

Also, as this is part of an assignment, it has been requested that I not use any BufferedReader or BufferedWriter.

Aucun commentaire:

Enregistrer un commentaire