?
Solved

Input and output in Java

Posted on 2003-02-28
14
Medium Priority
?
239 Views
Last Modified: 2010-03-31
A standard data processing task is to read and modify the contents of one file, writing the results to a second file. Write a Java program that performs this task, where
the names of the input file and output file are provided by the user on the command line when the program is run. This program should check that these two arguments are provided, that the first is a file that is not a directory, and that the second is not an existing file. Hint: the File class provides suitable methods.
the contents of the input file should be read in one byte at a time. Hint: read() either returns an integer between 0 and 255 (the value of an unsigned byte) or -1 (upon reaching the end of the input stream).
each byte read should be written to the output file as soon as it is available, except that (i) the value 36 should be changed to the value 163, (ii) the value 10 should be inserted after the value 12, and (iii) if the value 111 is immediately followed by the value 101, they should be replaced by the single value 248.
0
Comment
Question by:GFlexz
[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
  • 4
  • 4
  • 2
  • +3
14 Comments
 
LVL 92

Expert Comment

by:objects
ID: 8045594
This is not a site for doing your homework for you, in fact I think it is a breach of member agreement.
We can certainly help you with any problems you have implementing the above, but we're not here to write it for you.

Let me know any problems you have and I shall attempt to assist you.
0
 

Author Comment

by:GFlexz
ID: 8045613
Sorry look that problem I am having I have created the necessary command but it is giving me a null pinter.
Here is the file



/**
 *  Written by: GFlexz
 *  Date      : 23-02-2003
 *  Purpose   : Accept file names and compare
 *              name if not a directory and writer to and fro
 *              of the file name.
 */
 
 import java.net.*;
 import java.io.*;
 
public class InputOutput extends Object{
    public static void main (String[] args){
                               
        String first;
        String second;
        BufferedWriter  write = null;
        BufferedReader  read  = null;
        BufferedReader in = new BufferedReader ( new InputStreamReader ( System.in ));
       
       
       
        try{
            System.out.println( "Enter the first file name:  " );
            first = in.readLine().trim();
            System.out.println ( "Enter the second file name" );
            second = in.readLine().trim();
       
     
            File firstFile  = new File ( first  );
            File secondFile = new File ( second );
           
            if ( firstFile.isDirectory ( ) != true ){
                write = new BufferedWriter ( new FileWriter ( secondFile ) );
            }//End if
           
            if ( secondFile.isFile      ( ) != true ){
                read  = new BufferedReader ( new FileReader ( firstFile  ) );
            }//End if
            int Q;
            while(  (Q = read.read())  != -1 ){
                write.write ( Q );
             }
           
            write.close();
            read.close();

            }catch ( java.lang.SecurityException e ){
                System.out.println( e.getMessage ( ) );
           }catch ( java.io.IOException e ){
                System.out.println( e.getMessage() );
           }//End try

    } // main method
} //UniCodeConverter class
0
 
LVL 92

Expert Comment

by:objects
ID: 8045626
As you need to manipulate the file at the byte level, you should read using a stream, and not a reader.

> if ( secondFile.isFile      ( ) != true ){

This checks if the secondFile is not a file, not if it doesn't exist.

Instead try:

if (!secondFile.exists( )){
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 14

Expert Comment

by:Tommy Braas
ID: 8045778
On which line do you get the NullPointerException?
0
 

Author Comment

by:GFlexz
ID: 8045808
On this line
while(  (Q = read.read())  != -1 ){

And I am trying to write a loop that goes through a number and compare the next number i.e

if
int name[] = {2,12,19,30,12}
int name[1] = 12; is immediately followed by name[2] = 19
0
 
LVL 92

Accepted Solution

by:
objects earned 1000 total points
ID: 8045819
You also shouldn't do the file copy if either the f1st or 2nd file aren't valid (as this will result in an NPE).
eg. something like:
           
if ( firstFile.isDirectory ( ) != true &&
  secondFile.exists( ) != true){
       write = new FileOutputStream( secondFile ));
       read  = new FileInputStream( firstFile  ) );

       // perform copy

       write.close();
       read.close();
}

           
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 8045885
Or even better;

if ( firstFile.exists() && firstFile.isFile() && !secondFile.exists()){
      write = new FileOutputStream( secondFile ));
      read  = new FileInputStream( firstFile  ) );

      // perform copy

      write.close();
      read.close();
}
0
 

Assisted Solution

by:vfwood
vfwood earned 1000 total points
ID: 8048472
import java.net.*;
import java.io.*;

public class InputOutput extends Object{

     public static void main (String[] args){

          // vars
          String first;
          String second;
          BufferedReader in = new BufferedReader ( new InputStreamReader ( System.in ));
          FileInputStream fis;
          FileOutputStream fos;

          try{

               // get filenames...
               System.out.println( "Enter the first file name:  ");
               first = in.readLine().trim();
               System.out.println ( "Enter the second file name");
               second = in.readLine().trim();

               // create file objects
               File firstFile  = new File(first);
               File secondFile = new File(second);

               // File.isFile() checks both that file exists and is a file (not a dir)
               if (firstFile.isFile() && (! secondFile.exists()))     {
                    System.out.println("Getting streams");
                    // get streams...
                    fis = new FileInputStream(firstFile);
                    fos = new FileOutputStream(secondFile);
                    byte b;
                    while ((b = (byte)fis.read()) != -1) {
                         // here we determine what to do with output
                         switch (b) {
                              case 36:
                                   fos.write(163);
                                   break;
                              case 12:
                                   fos.write(12);
                                   fos.write(10);
                                   break;
                              default:
                                   fos.write(b);
                                    break;
                         }
                    }
               } else {
                    // doesnt meet criteria
               }
          }
          catch ( java.lang.SecurityException e ){
               System.out.println( e.getMessage ( ) );
          }
          catch ( java.io.IOException e ){
               System.out.println( e.getMessage() );
          }
          finally {
               if (fis != null) {
                    fis.close();
                    fos.close();
               }
          }

     }
}

---

I'll let you work out how to replace the two bytes with one but i think this explains the file handling
0
 

Author Comment

by:GFlexz
ID: 8048573
Vfwood

Thanks for your answer that is what I was looking for.  Before I award you the point which you deserve please can you tell me how to change the value 111 is immediately followed by the value 101, they should be replaced by the single value 248.

Thanks
GFlexz
0
 
LVL 92

Expert Comment

by:objects
ID: 8048934
vfwood,

Please be aware that doing peoples homework is not permitted on this site.
0
 

Author Comment

by:GFlexz
ID: 8059927
No one is doing my homework for me wfwood. I am only getting some concepts of my actual program.  All the questions I ask here is design by me and variably it is not my homework but rather a very small idea in doing my project.  If you have a problem with that then It is a pity.  My project is to design and deploy simulations distributed system.  If you think any of my question is regarding my assignment. Contact www.sbu.ac.uk and follow the link(s) to academic misconduct code.  I am sure there will be very interested hearing from you.  Yes remind them that one student doing his thesis on distributed system is getting help from objects & wfwood.

Thanks
GFlexz

Can someone else please help in how to change the value 111 is immediately followed by the value 101.
0
 

Expert Comment

by:CleanupPing
ID: 9059007
GFlexz:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9677803
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 between objects, orangehead911, and vfwood

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TimYates
EE Cleanup Volunteer
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
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…
Suggested Courses
Course of the Month11 days, 5 hours left to enroll

770 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