Reading and Writing files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • r035198x
    MVP
    • Sep 2006
    • 13225

    Reading and Writing files

    The program below simply reads a file called FileTest1.java( itself) and prints it to the console

    Code:
     
    
    import java.util.Scanner;
    import java.io.*;
    class FileTest1 {
     public static void main(String args[]) {
      Scanner inputFile = null;
      try {
       inputFile = new Scanner(new File("FileTest1.java"));
       while(inputFile.hasNext()) {
    	System.out.println(inputFile.next());
       }
    
      }
      catch(FileNotFoundException fNFE) {
       System.out.println("The file was not found");
      }
      finally {
       inputFile.close();
      }
    
     } 
    
    }
    Two methods of the Scanner class were used here hasNext and next.
    You should be able to see what these methods are doing here if not then you can check with the Scanner page on sun's Java API.
    This is the recommended way of reading a file these days.

    To write to a file, use the FileWriter class wrapped in a BufferedWriter

    Code:
     
    
    public static void writeFile(String fileName) {
     BufferedWriter br = null;
     try {
      br = new BufferedWriter(new FileWriter(fileName));
      String[] semiFinals = {"Australia", "West Indies", "South Africa", "Sri Lanka"};
      for(String s : semiFinals) {
       br.write(s);
       br.write(System.getProperty("line.separator"));
      }
      br.close();
     }
     catch(IOException iO) {
      System.out.println("The file could not be created/opened/closed");
     }
    }

    Notice the use of System.getPrope rty("line.separ ator"); to write a return
    This method of opening a file overrides the data that was on the file.
    To open the file in append mode, simply use
    Code:
    br = new BufferedWriter(new FileWriter(fileName, true));
    These approaches should not be used for manipulating .doc, pdf, xls e.t.c Instead one should use more specific packages
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    I don't want to exhibit myself as a nitpicker but why don't you just simply use
    a BufferedReader for this instead of a Scanner. BufferedReaders are available
    in Java 1.4 and before while those Scanners are only available starting from
    Java 1.5 and up. BufferedReaders are much simpler too.

    kind regards,

    Jos (<--- nitpicker ;-)

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by JosAH
      I don't want to exhibit myself as a nitpicker but why don't you just simply use
      a BufferedReader for this instead of a Scanner. BufferedReaders are available
      in Java 1.4 and before while those Scanners are only available starting from
      Java 1.5 and up. BufferedReaders are much simpler too.

      kind regards,

      Jos (<--- nitpicker ;-)

      And for those who prefer the nitpicker's advice

      Code:
       
      import java.io.*;
      class FileTest1 {
      public static void main(String args[]) {
      BufferedReader inputFile = null;
      try {
      inputFile = new BufferedReader (new FileReader("FileTest1.java"));
      while((String line = inputFile.readLine()) != null) {
      		 System.out.println(line);
      }
       
      }
      catch(FileNotFoundException fNFE) {
      System.out.println("The file was not found");
      }
      catch(IOException iO) {
      	System.out.println("IO error");
      }
      finally {
      inputFile.close();
      }
       
      } 
       
      }

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by r035198x
        And for those who prefer the nitpicker's advice
        :-)

        kind regards,

        Jos

        ps. while I'm at it, other IOExceptions can be thrown too you know ;-)

        Comment

        • r035198x
          MVP
          • Sep 2006
          • 13225

          #5
          Originally posted by JosAH
          :-)

          kind regards,

          Jos

          ps. while I'm at it, other IOExceptions can be thrown too you know ;-)
          But of course Jos.

          At which point I will now have to edit the post.

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by r035198x
            But of course Jos.

            At which point I will now have to edit the post.
            I'm sorry for stirring this all up; I'm a nasty nitpicker ;-)

            kind regards,

            Jos

            Comment

            • saraali
              New Member
              • Mar 2007
              • 3

              #7
              hello every body

              I need a help please help me if you can
              what functions can we use to send multimedia (vedio,oudio,im eges) using java through socket .


              send any thing about this subject to my e-mail : <email removed:Against site rules>
              thanks ............... .

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Originally posted by saraali
                hello every body

                I need a help please help me if you can
                what functions can we use to send multimedia (vedio,oudio,im eges) using java through socket .


                send any thing about this subject to my e-mail : dreams294@hotma il.com
                thanks ............... .
                Please start you own topic for your question; don't pollute anyone else's topic.

                kind regards,

                Jos

                Comment

                • quadelirus
                  New Member
                  • Apr 2007
                  • 1

                  #9
                  Originally posted by JosAH
                  I don't want to exhibit myself as a nitpicker but why don't you just simply use
                  a BufferedReader for this instead of a Scanner.
                  Can't the Scanner class be a better option if, for instance, someone wanted to easily extract various forms of data from the input say one structured with integers floats and strings all on the same line? Of course you CAN use the BufferedReader, but the scanner may be a better choice for an actual solution to a problem.

                  Just my 2c.

                  Comment

                  • JosAH
                    Recognized Expert MVP
                    • Mar 2007
                    • 11453

                    #10
                    Originally posted by quadelirus
                    Can't the Scanner class be a better option if, for instance, someone wanted to easily extract various forms of data from the input say one structured with integers floats and strings all on the same line? Of course you CAN use the BufferedReader, but the scanner may be a better choice for an actual solution to a problem.

                    Just my 2c.
                    Sure, a Scanner would be much better for that purpose, but for the purpose
                    shown in the article a Scanner would be overkill; that's why I was nitpicking ;-)
                    (and besides that, Scanners are only here with us, starting at Java 1.5)

                    kind regards,

                    Jos

                    Comment

                    • jyohere
                      New Member
                      • Apr 2007
                      • 73

                      #11
                      Originally posted by JosAH
                      Sure, a Scanner would be much better for that purpose, but for the purpose
                      shown in the article a Scanner would be overkill; that's why I was nitpicking ;-)
                      (and besides that, Scanners are only here with us, starting at Java 1.5)

                      kind regards,

                      Jos
                      I want to read on a field by field basis say

                      Name Age DateOfBirth

                      Jyo 25 28-11-82
                      Ram 30 20-12-81



                      say I want to read the above file and find out the entries whose DOB is between two given dates

                      Comment

                      • JosAH
                        Recognized Expert MVP
                        • Mar 2007
                        • 11453

                        #12
                        Originally posted by jyohere
                        I want to read on a field by field basis say

                        Name Age DateOfBirth

                        Jyo 25 28-11-82
                        Ram 30 20-12-81



                        say I want to read the above file and find out the entries whose DOB is between two given dates
                        Read the API docs for the Scanner class and use the code supplied
                        in this tip of the week to read all non-white space tokens. Oh, before I forget,
                        the FileReader or FileInputStream classes top it all off.

                        kind regards,

                        Jos

                        Comment

                        • nomad
                          Recognized Expert Contributor
                          • Mar 2007
                          • 664

                          #13
                          Hey a great posting would be how to use a Arraylist.
                          code to build arraylist
                          code to create output file and write arraylist
                          code to read input files and rebuild an Arraylist
                          code to display the contents on an arraylist.

                          This was a hard one for me to understand, and sometimes it still is.

                          nomad.
                          just my two cents.

                          Comment

                          • JosAH
                            Recognized Expert MVP
                            • Mar 2007
                            • 11453

                            #14
                            Originally posted by nomad
                            Hey a great posting would be how to use a Arraylist.
                            code to build arraylist
                            code to create output file and write arraylist
                            code to read input files and rebuild an Arraylist
                            code to display the contents on an arraylist.

                            This was a hard one for me to understand, and sometimes it still is.
                            Why don't you try it yourself? You try to write a nice concise article; post your
                            attempts in this forum and I for one will help you out when you're stuck. When
                            the article is finished you can stick it in the Articles section. deal?

                            kind regards,

                            Jos

                            Comment

                            • nomad
                              Recognized Expert Contributor
                              • Mar 2007
                              • 664

                              #15
                              Originally posted by JosAH
                              Why don't you try it yourself? You try to write a nice concise article; post your
                              attempts in this forum and I for one will help you out when you're stuck. When
                              the article is finished you can stick it in the Articles section. deal?

                              kind regards,

                              Jos
                              How did I get invloved with this. Heck I'm just starting out in Java. I have only done a several projects. Two with Arraylist and I had a very very hard time doing those....I don't even know if I did those right, because the instructor has not grade them.
                              Besides I think the viewer would rather see ane Expert like you do it Jos.

                              nomad.
                              Maybe in a few months when I get more under my belt. I would do one for Flash or HTML...

                              Comment

                              Working...