Question

Input and output in Java

Asked by: GFlexz

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.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-02-28 at 16:20:50ID20534287
Topic

Java Programming Language

Participating Experts
5
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Java - unsigned short
    Like we can define an unsigned short in C, how do we do that in java? //C definition unsigned short my_short_int; //Java ?
  2. Integer ...
    Hi i am having problems with java type converstions. Ok firs question i have is this. 1) Integer j = new Integer(); // Why can't i assign a value to this integer variable now ? then i was trying to convert that value from integer to binary. here is how i tried to do it. S...
  3. Unsigned numbers
    I need to use unsigned int and unsigned long in java! ???
  4. Convert String to Unsigned Long Integer
    I am writing and RPC in C , and I am converting the string from the host type to network type to be sent over the network using the htonl function , now I want to convert it back to the string format using the ntohl function .The problem is since the ntonl function take only ...
  5. Java unsigned char (??)
    Does java have the variable 'unsigned char' as c does?... (without using JNI!)

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: objectsPosted on 2003-02-28 at 16:31:44ID: 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.

 

by: GFlexzPosted on 2003-02-28 at 16:36:02ID: 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

 

by: objectsPosted on 2003-02-28 at 16:41:09ID: 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( )){

 

by: orangehead911Posted on 2003-02-28 at 17:20:24ID: 8045778

On which line do you get the NullPointerException?

 

by: GFlexzPosted on 2003-02-28 at 17:29:49ID: 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

 

by: objectsPosted on 2003-02-28 at 17:33:05ID: 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();
}

           

 

by: orangehead911Posted on 2003-02-28 at 17:50:20ID: 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();
}

 

by: vfwoodPosted on 2003-03-01 at 10:41:38ID: 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

 

by: GFlexzPosted on 2003-03-01 at 11:08:18ID: 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

 

by: objectsPosted on 2003-03-01 at 12:44:28ID: 8048934

vfwood,

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

 

by: GFlexzPosted on 2003-03-03 at 12:54:48ID: 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.

 

by: CleanupPingPosted on 2003-08-03 at 02:40:25ID: 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.

 

by: TimYatesPosted on 2003-11-04 at 03:36:23ID: 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

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...