Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

A simple java program for file operation.

Posted on 2006-04-22
9
Medium Priority
?
238 Views
Last Modified: 2010-03-31
Sorry a newbie question....
I have an exercise folder and inside that 2 java programs as follows.....

First one is merge.java as follows,

import java.io.*;
import exc.*;
class merge
{

      public static void main(String[] args) throws excep1
      {
            System.out.println("Exercise for merging file1 and file2 into result !");
            
            try
            {
                  FileOutputStream fos = new FileOutputStream("result.txt", true);
                  DataOutputStream dos = new DataOutputStream(fos);

                  FileInputStream fis1 = new FileInputStream("file1.txt");
                  DataInputStream dis1 = new DataInputStream(fis1);
                  String s = "";
                  int count = 0;
                  while ((s = dis1.readLine()) != null)
                  {
                        s = s + "\n";
                        count++;
                  }
                  if (count >= 5)
                        
                  {
                        dos.writeBytes(s);
                        s="";
                        count=0;
                  }
                  else

                  {
                        throw new excep1("Less than 5 lines not allowed in file1");
                  }

            FileInputStream fis2 = new FileInputStream("file2.txt");
            DataInputStream dis2 = new DataInputStream(fis2);
                  while((s = dis2.readLine()) != null)
                  {
                        s = s + "\n";
                        count++;
                  }
                  if (count >= 5)
                        
                  {
                        dos.writeBytes(s);
                        s="";
                        count=0;
                  }
                  else

                  {
                        throw new excep1("Less than 5 lines not allowed in file2");
                  }

            }

            catch (Exception e)
            {
                  e.printStackTrace();
            }
      }
}


And another excep1.java file....

package exc;
public class excep1 extends Exception
{
      public excep1(Exception e)
      {
            e.printStackTrace();
      }

}


So what I want is.... just throw my user defined exception when less than 5 lines and print it in excep1 class. Remember I dont want system exception to be printed, rather just to print my message alone !

I compiled using "javac *.java" and I'm getting compile errors. Anything wrong in the program? Please correct it if I'm wrong.

Thanks.


0
Comment
Question by:gopikrish
  • 5
  • 4
9 Comments
 
LVL 14

Expert Comment

by:hoomanv
ID: 16516476
The .java file has to be within the correct directory structure, defined by
its package, for compilation

so excep1.java must be in directory exc
and then just javac Merge.java
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16516484
also you need to add these lines to excep1

      public excep1(String msg) {
            super(msg);
      }

because in the code you are attempting to construct it by String parameters
0
 

Author Comment

by:gopikrish
ID: 16516550
Ok fine... On execution the following error is shown,

Exercise for merging file1 and file2 into result !
java.lang.NullPointerException
        at java.io.DataOutputStream.writeBytes(Unknown Source)
        at merge.main(merge.java:27)

Anything wrong ?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:gopikrish
ID: 16517781
Well anyone can help me please?
0
 
LVL 14

Accepted Solution

by:
hoomanv earned 200 total points
ID: 16518029
import java.io.*;
import exc.*;
class merge
{

     public static void main(String[] args) throws excep1 {
          System.out.println("Exercise for merging file1 and file2 into result !");
         
          try {
                     StringBuilder content = new StringBuilder();
                     String line;
               int count = 0;
                    
               FileOutputStream fos = new FileOutputStream("result.txt", true);
               DataOutputStream dos = new DataOutputStream(fos);

               FileInputStream fis1 = new FileInputStream("file1.txt");
               DataInputStream dis1 = new DataInputStream(fis1);
               
               while ((line = dis1.readLine()) != null) {
                              content.append(line);
                    content.append("\r\n");
                    count++;
               }
                     dis1.close();
                    
               if (count >= 5) {
                    dos.writeBytes(content.toString());
                              content.delete(0, content.length());
                    count=0;
               }
               else {
                              dos.close();
                    throw new excep1("Less than 5 lines not allowed in file1");
               }

                    FileInputStream fis2 = new FileInputStream("file2.txt");
                    DataInputStream dis2 = new DataInputStream(fis2);
               while((line = dis2.readLine()) != null) {
                    content.append(line);
                    content.append("\r\n");
                    count++;
               }
                     dis2.close();
                    
               if (count >= 5) {
                    dos.writeBytes(content.toString());
                    count=0;
               }
               else {
                              dos.close();
                    throw new excep1("Less than 5 lines not allowed in file2");
               }

                        dos.close();
          }
          catch (Exception e) {
               e.printStackTrace();
          }
     }
}
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16518061
1)
> java.lang.NullPointerException

it was because of this line
while ((s = dis1.readLine()) != null)
at the last line s will become null
also you have to store the read lines some where else than s because s will be changed in each call to s = dis1.readLine()
I changed it to StringBuilder as it is more efficient than just saying s += line + "\n";

2)
make sure you close the open OutputStreams when you dont need them any more

0
 

Author Comment

by:gopikrish
ID: 16518277
Nice !
Now its writing to result.txt

But when my file1 is having 4 lines and when I executed my program, the following is getting displayed....

Exercise for merging file1 and file2 into result !
Less than 5 lines not allowed in file1
exc.excep1
        at merge.main(merge.java:37)

I just want my message alone to be printed and dont want system message to be printed. That is I want "Less than 5 lines not allowed in file1" and not "exc.excep1
        at merge.main(merge.java:37)"

My excep1 class is as follows....
package exc;
public class excep1 extends Exception
{
      public excep1(String msg) {
                    System.out.println(msg);
  }
}

How to make it please ?
Thanks.
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16518293
you dont need to throw any exception for this purpose
a Sysmte.out.println("Less than 5 lines not allowed in file2"); would be enough
but if you are forced to throw exception
just change this line
e.printStackTrace();
to
System.out.println(e.getMessage());
0
 

Author Comment

by:gopikrish
ID: 16518375
ok thanks a lot !
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month15 days, 2 hours left to enroll

578 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