Reading and Writing files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #16
    Originally posted by nomad
    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.
    Stage fright? ;-) I promised I'd help you out and maybe during the 'making' of
    the article others will join us in this forum. It could be fun. I promise I won't
    'attack' you ;-) Why not give it a try? All we have to come up with now is a
    nice, simple problem/project that naturally has to do with Lists.

    kind regards,

    Jos

    Comment

    • nomad
      Recognized Expert Contributor
      • Mar 2007
      • 664

      #17
      Originally posted by JosAH
      Stage fright? ;-) I promised I'd help you out and maybe during the 'making' of
      the article others will join us in this forum. It could be fun. I promise I won't
      'attack' you ;-) Why not give it a try? All we have to come up with now is a
      nice, simple problem/project that naturally has to do with Lists.

      kind regards,

      Jos
      OK Jos...
      I making a arraylist program for you It might be too long but it is one of my assignments. I could shorten it.
      Anyways here is the code so far, but I'm having problem

      I can not invoke the findPerson method. It should work because I have done this in the past.
      I did a debug and got this error.

      <terminated>Emp loyeeData (1) [Java Application]
      <disconnected>a rrayproject.Emp loyeeData at localhost:1253
      <terminated, exit value: 0>C:\Program Files\EasyEclip se Desktop Java 1.2.1\jre\bin\j avaw.exe (May 9, 2007 2:04:22 PM)

      I have attached my whole project and if someone can help me that would be great..


      Code:
      class PersonClass {
          private String empid;
          private String lname;
          private String fname;
          private String street;
          private String city;
          private String state;
          private String zip;
          private double payrate;
          private int yearsworked;
          public PersonClass(String id) {
      		empid = id;
          }
          public PersonClass(String id, String ln, String fn, String st, String ct, String se, String zp, double pr, int yw) {
          	empid = id;
          	lname = ln;
              fname = fn;
              street = st;
              city = ct;
              state = se;
              zip = zp;
              payrate = pr;
              yearsworked = yw;
       
          }
       
          // accessors
          public String getID() {return empid;}
       
          public String getFname() {return fname;}
       
          public String getLname() {return lname;}
       
          public String getStree() {return street;}
       
       
          public String getCity() {return city;}
       
          public String getState() {return state;}
       
          public String getZip() {return zip;}
       
          public double getPayrate() {return payrate;}
       
          public int getYearsworked() {return yearsworked;}
       
       
      }
       
       
      public class EmployeeData {
          static ArrayList<PersonClass> arlist;
          static Scanner kbd;
       
          public static PersonClass makePerson() {
              PersonClass temp = null;
       
              // prompt for data
              String id;
              String ln;
              String fn;
              String st;
              String se;
              String ct;
              String zp;
              double pr;
              int years;
       
              System.out.print("Enter ID Number ==>");
              id = kbd.next();
       
              System.out.print("Enter Last Name ==>");
              ln = kbd.next();
       
              System.out.print("Enter First Name ==>");
              fn = kbd.next();
       
              System.out.print("Enter the address==>");
              st = kbd.next();
       
              System.out.print("Enter City ==>");
              ct = kbd.next();
       
              System.out.print("Enter State ==>");
              se = kbd.next();
       
              System.out.print("Enter Zip ==>");
              zp = kbd.next();
       
              System.out.print("Enter payrate as double ==>");
              pr = kbd.nextDouble();
       
              System.out.print("Enter years worked ==>");
              years = kbd.nextInt();
       
              // make an object
              temp = new PersonClass(id, ln,fn,st,ct,se, zp, pr,years);
       
              return temp;
          }
       
          public void displayMatch() {
       
          String id_flag = "";
      	Scanner kbd = new Scanner(System.in);
      	System.out.println("Enter your info please ie: AB1234: ");
      	id_flag = kbd.next();
      	boolean notfound = true;
      	for (PersonClass e : arlist) {
      		String emp = e.getID();
      		if (emp.equals(id_flag)) {
      			System.out.println("Hello" + ("e.lname"));
      			notfound = false;
      		}
      	}
      	if (notfound == true) {
      		System.out.println("Error - Employee not found");
      		// back to menu?
      }
       
          }//close findperson
       
          public static void main(String[] args) {
          	EmployeeData emp = new EmployeeData();
              // make array list object
              arlist = new ArrayList<PersonClass>();
       
              // make a scanner
              kbd = new Scanner(System.in);
       
              int choice;
      		System.out.println("Make a Section: ");
      		System.out.println("1. Enter Employees ");
      		System.out.println("2. Find Employees ");
      		System.out.println("3. Exit this Program ");
      		System.out.print("\nPlease press Enter afer each response");
      		System.out.println("Enter your chose please: ");
      		choice = kbd.nextInt();
      		kbd.nextLine();
      		if (choice == 1) { // if 1 is select go to makePerson
       
              // create people until select stop
              boolean endData = false;
       
              while (!endData) {
                  PersonClass temp = makePerson();
                  arlist.add(temp);
                  System.out.println("Add More employees (Y/N)-->");
       
                  String ans = kbd.next();
       
                  if (ans.equalsIgnoreCase("N")) {
                      endData = true;
                  }
              }//close while loop
              if (choice == 2) { // if 2 is select go to find
              	emp.displayMatch();
       
       
              }// close the choice==2
      		if (choice == 3) {
      			System.out.printf("Good bye");
      		}// close the choice == 3
       
       
              // print out all elements of array list
              for (PersonClass idx : arlist) {
              	System.out.printf("Employee Id is %n", idx.getID());
                      System.out.printf("Name is %s - %s%n", idx.getFname(),idx.getLname());
                      System.out.printf("Street is %s%n", idx.getStree());
                      System.out.printf("City is %s%n", idx.getCity());
                      System.out.printf("State is %s%n", idx.getState());
                      System.out.printf("Zip Code is %s%n", idx.getZip());
                      System.out.printf("Payrate is %8.2f%n", idx.getPayrate());
                      System.out.printf("Years worked are %d\n", idx.getYearsworked());
                      System.out.println("--------------------");
              }
          }
      }
      }


      Thanks a bunch
      nomad

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #18
        I created a new thread for Nomad's Article under construction so there'll be no
        need anymore to hijack this thread.

        kind regards,

        Jos

        Comment

        • JCEtajin
          New Member
          • Sep 2007
          • 6

          #19
          Originally posted by r035198x
          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
          how to apply in JFileChooser?.. that it can read the file that was selected.

          Comment

          • chaarmann
            Recognized Expert Contributor
            • Nov 2007
            • 785

            #20
            Usually loading a whole file at once is faster than looping through it line by line. Especially if the file resides on a network device.

            Here is the code:
            Code:
            // check existence
            File file = new File(sourceFileName);
            if (! file.exists()) throw new IOException("ERROR: no such source file: " + sourceFileName);
            
            // read as string
            FileInputStream fileInputStream = new FileInputStream(sourceFileName);
            byte data[] = new byte[fileInputStream.available()];
            fileInputStream.read(data);
            String content = new String(data);
            
            // do whatever you want with the result
            System.out.println("File contains:" + content);

            Comment

            Working...