tags:

views:

270

answers:

9

Question: write a Java program which accepts s list of existing text files from command line args and concatenates the contents of all files in "Master.txt".

It gives error while testing 4 endsWith(".txt"). Kindly correct it

import java.io.*;
class FileConcat
{
 public static void main(String[] args)
 {
  FileOutputStream fout;
  FileInputStream fin,fin1;
  File f;
  int b; 
  try
  {
   //open Master file
   try
   {
    fout=new FileOutputStream("Master.txt"); 
   }
   catch(Exception e)
   {
    System.out.print(e.getMessage());
   }
   //traverse all args, check if valid text file, if yes, concatinate
   for(int j=0;j<args.length;j++)
   {
    f=new File(args[j]);
    if(f.isFile()==true)
    {
     if((args[j].endsWith(".txt"))==true)
     {
      try
      {
       fin=new FileInputStream(args[j]);
      }
      catch(Exception e)
      {
       System.out.print("Error Opening "+args[j]);
      }
      while((b=fin.read())!=-1)
      {
       char ch=(char) b;
       fout.write(ch);
      }
     }
    fin.close();
    }
   }
   fout.close();
   fin1=new FileInputStream("Master.txt"); 
   while((b=fin1.read())!=-1)
   {
    char ch=(char) b;
    System.out.print(ch);
   }
   fin1.close();
  }
  catch(Exception e)
  {
   System.out.println(e.getMessage());
  }
 }
}

C:\j2sdk1.4.1_01\bin>javac FileConcat.java
FileConcat.java:38: variable fin might not have been initialized
                                                while((b=fin.read())!=-1)
                                                         ^
FileConcat.java:41: variable fout might not have been initialized
                                                        fout.write(ch);
                                                        ^
FileConcat.java:44: variable fin might not have been initialized
                                fin.close();
                                ^
FileConcat.java:47: variable fout might not have been initialized
                        fout.close();
                        ^
4 errors

How do I check if fin is assigned a value or not?

+1  A: 

If fout = new FileOutputStream("Master.txt"); throws an exception then fout is undefined but you are still attempting to write to the file.

Similarly if fin = new FileInputStream(args[j]); throws an exception then fin is undefined but you still attempt to read from the file.

You could enclose the whole loop in the try block, or just declare main to throw IOException.

I also recommend moving the calls to close() into finally blocks and removing the redundant "==true" from some of the tests.

import java.io.*;
public class FileConcat
{
  public static void main(String[] args)
  {
    FileOutputStream fout;
    FileInputStream fin,fin1;
    File f;
    int b; 

    //open Master file
    try
    {
      fout=new FileOutputStream("Master.txt"); 
      try
      {
        //traverse all args, check if valid text file, if yes, concatinate
        for(int j=0;j<args.length;j++)
        {
          f=new File(args[j]);
          if(f.isFile())
          {
            if(args[j].endsWith(".txt"))
            {
              try
              {
                fin=new FileInputStream(args[j]);
                try
                {
                  while((b=fin.read())!=-1)
                  {
                    char ch=(char) b;
                    fout.write(ch);
                  }
                }
                catch (IOException e)
                {
                  e.printStackTrace();
                }
                finally
                {
                  fin.close();
                }
              }
              catch(Exception e)
              {
                System.err.println("Error opening "+args[j]+" for input");
              }
            }
          }
        }
      }
      finally
      {
        fout.close();
      }
      fin1=new FileInputStream("Master.txt"); 
      while((b=fin1.read())!=-1)
      {
        char ch=(char) b;
        System.out.print(ch);
      }
      fin1.close();
    }
    catch(Exception e)
    {
      System.err.println("Error opening Master.txt for output");
    }
  }
}
finnw
A: 

To answer your question at its face value, you can check if fin is assigned a value using

if (null == fin)

The actual cause, though, is because you're continuing execution if an exception is thrown.

 try
  {
   fin=new FileInputStream(args[j]);
  }
  catch(Exception e)
  {
   System.out.print("Error Opening "+args[j]);
  }

The above block doesn't set fin if an Exception is thrown, yet you access fin in the very next line. This also applies to fout and fin1.

You can nest other code in a try block; the is actually recommended if you're using resources that may throw exceptions when access them.

R. Bemrose
That will only work if fin and fout are also initialised to null.
finnw
+1  A: 

Your issue is with the following section (and other similar ones):

try
{
  fin=new FileInputStream(args[j]);
}
catch(Exception e)
{
  System.out.print("Error Opening "+args[j]);
}

If an exception is thrown, then fin will not have been initialised with a value. However, if an exception is thrown, then arguably your program cannot continue. Therefore I think you should remove the try/catch and just declare that your main method throws IOException.

Simon Nickerson
A: 

Just set the variables at the beginning of your method:

public static void main(String[] args) {
    FileOutputStream fout = null;
    FileInputStream fin = null;
    FileInputStream fin1 = null;
    ...
romaintaz
A: 

Initialize the variables thus:

FileOutputStream fout = null;
FileInputStream fin = null, fin1 = null;
Vijay Dev
+4  A: 

The problem is that you don't assign anything at all to fin and fout when you declare them, you only assign to them in a try{} block, and the code that subsequently uses them is outside the try{} block; so if an exception is thrown inside the try{} block, the program will continue regardless and attempt to use the uninitialised values.

Your options are:

  • Move the code trying to use these variables inside the try{} block where they are initialised
  • Assign null to these variables when declaring them, and place the code that tries to use them in an if (variable != null) {} block.
  • Make the catch() clauses perform some action that guarantees the code that would otherwise try to use uninitialised variables does not execute, e.g. exit the program
  • Just get rid of the try.. catch clauses and declare the whole method as throwing those exceptions
moonshadow
Unrelated to the answer, but I love the Cat Stevens reference in your name (or, alternatively, the PS238 reference)
aperkins
+2  A: 

There's no need to say:

if (b == true)

When b is some boolean. This is equivalent to:

if (b)

This doesn't answer your question (as others already have) but might be useful for you anyway

oxbow_lakes
A: 

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class ConcatFiles {

public static String masterFile;

public static void main(String[] args) throws Exception
{
 MasterFile();
}

public static void MasterFile() throws Exception
{
 System.out.println("Enter Master File Name:");
 Scanner readMasterFileName = new Scanner(System.in);
 masterFile = readMasterFileName.next();
 if (new File(masterFile).exists() && masterFile.contains(".txt"))
 readFileName();
 else
 {
  if (masterFile.contains(".txt"))
  {
   new File(masterFile).createNewFile();
   System.out.println("Master File Created");
   readFileName();
  }
  else
  {
   System.out.println("Invalid File or Input");
   MasterFile();
  }
 }
}
public static void readFileName() throws Exception
{
 System.out.println("Enter File Names:");
 Scanner readOtherFiles = new Scanner(System.in);
 String cmd = readOtherFiles.next();

 if (cmd.equalsIgnoreCase("Exit"))
  System.exit(0);
 else
  if (cmd.equalsIgnoreCase("New"))
   MasterFile();
  else
   if (cmd.contains(".txt") && new File(cmd).exists())
   concatFile(cmd);
   else
   {
    System.out.println("Invalid Input or File");
    readFileName();
   }
}
public static void concatFile(String otherFiles)throws Exception
{
 BufferedWriter out = new BufferedWriter(new FileWriter(masterFile, true));
    File readFiles = new File(otherFiles);
    Scanner reader = new Scanner(readFiles);
    while(reader.hasNext())
    {
        out.write(reader.nextLine()+"\n");
    }
    out.close();
 readFileName();
}

}

A: 

you add return statement in catch block...rest is fine.... eg :

try{

} catch(ExcepttionName exObject) { statements; return;

}

you have to add return in every catch() block.