Read a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jromero
    New Member
    • Sep 2007
    • 16

    #1

    Read a file

    My code
    [

    public class Student{
    private String lastName;
    private String firstName;
    private String middleName;
    private int sid;
    private double units;
    private String Programs;


    public Student(){
    this( "", "", "", 0, 0.0, "");
    }

    public Student (String lastName, String firstName, String middleName, int sid, double units, String Programs )
    {
    //setLastName(las tName);
    setFirstName(fi rstName);
    setMiddleName(m iddleName);
    setsid(sid);
    setunits(units) ;
    setPrograms(Pro grams);

    }

    public void setLastName(Str ing lastName){
    lastName = lastName;
    }

    public String getLastName(){
    return lastName;
    }

    public void setFirstName(St ring firstName){
    firstName = firstName;
    }

    public String getFirstName(){
    return firstName;
    }

    public void setMiddleName(S tring middleName){
    middleName = middleName;
    }

    public String getMiddleName() {
    return middleName;
    }

    public void setsid(int sid){
    sid = sid;
    }
    public int getsid(){
    return sid;
    }


    public void setunits(double units){
    units = units;
    }


    public double getunits()
    {
    return units;
    }


    public void setPrograms(Str ing Programs){
    Programs = Programs;
    }

    public String getPrograms(){
    return Programs;
    }

    }

    ]
    Another class
    [

    import java.io.File;
    import java.io.IOExcep tion;
    import java.util.Scann er;

    public class Roaster {

    Student st[] = new Student[100];

    /* public static void copyLines() throws IOException {
    BufferedReader inputStream = null;
    PrintWriter outputStream = null;

    try {
    inputStream =
    new BufferedReader( new FileReader("roa ster.txt"));

    for(i=0;i<no.of lines;i++)
    {
    addstudent(fir,
    }
    outputStream =
    new PrintWriter(new FileWriter("cha racteroutput.tx t"));

    String l;
    while ((l = inputStream.rea dLine()) != null) {

    outputStream.pr intln(l);
    }
    } finally {
    if (inputStream != null) {
    inputStream.clo se();
    }
    if (outputStream != null) {
    outputStream.cl ose();
    }
    }
    }*/

    public void addStudentfromF ile() throws IOException
    {
    Scanner inputStream = null;
    try {
    inputStream =
    new Scanner(new File("roaster.t xt"));
    int noofstu = 1;

    while (inputStream.ha sNext()) {

    String temp = inputStream.nex t();
    String[] name = null;
    name = temp.split(",") ;
    /* System.out.prin tln(name[0]);
    System.out.prin tln(name[1]);
    System.out.prin tln(inputStream .next());

    System.out.prin tln(inputStream .nextInt());

    System.out.prin tln(inputStream .nextDouble());
    System.out.prin tln(inputStream .next());*/
    st[noofstu-1] = new Student(name[0], name[1], inputStream.nex t(),inputStream .nextInt() , inputStream.nex tDouble(),input Stream.next());
    noofstu++;
    }
    } finally {
    if (inputStream != null) {
    inputStream.clo se();
    }

    }

    }

    public int getStudentno(){
    //getStudent = new Student;
    return st.length;

    }


    public static void main(String[] args) {


    }
    }
    ]
    Another class for testing
    [
    import java.io.Buffere dInputStream;
    import java.io.Buffere dReader;
    import java.io.DataInp utStream;
    import java.io.File;
    import java.io.FileInp utStream;
    import java.io.FileRea der;
    import java.io.IOExcep tion;

    public class RoasterTest {

    public static void main (String[] args) throws Exception{
    File RoasterTest = new File( "roaster.tx t" );
    if ( RoasterTest.exi sts() )
    {
    // Create the buffered reader for reading the file
    BufferedReader inFile = new BufferedReader( new FileReader( RoasterTest ) );



    // Get the first line of the file
    String line = inFile.readLine ();

    // If line is not end of file continue
    while ( line != null )
    {
    // Create a StringTokenizer with a colon sign as a delimiter
    java.util.Strin gTokenizer st =
    new java.util.Strin gTokenizer( line, ":" );

    // Display the content of the first token
    System.out.prin t( " Name: " + st.nextToken() );

    // Display the total number of tokens remaining this string
    int numScores = st.countTokens( );

    // Initialize the sum to zero
    int sum = 0;

    // Get each score, add it to the sum and print it
    for ( int i=1; i <= numScores; i++ )
    {
    int score = Integer.parseIn t( st.nextToken() );
    sum += score;
    }

    // Display the average score for this student
    System.out.prin tln( " average = " + sum/numScores );

    // Read next line of the file
    line = inFile.readLine ();

    } // end while not at end of file

    // Close the BufferedReader
    inFile.close();

    // try {
    // RoasterTest.clo ne();
    // } catch (IOException ioe) {

    } // end if the grade file doesn't exist

    }

    }

    ]

    My test class does not read student class or roaster class .. I know I am missing something but I am loss
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    Originally posted by Jromero
    My code
    [

    public class Student{
    private String lastName;
    private String firstName;
    private String middleName;
    private int sid;
    private double units;
    private String Programs;


    public Student(){
    this( "", "", "", 0, 0.0, "");
    }

    public Student (String lastName, String firstName, String middleName, int sid, double units, String Programs )
    {
    //setLastName(las tName);
    setFirstName(fi rstName);
    setMiddleName(m iddleName);
    setsid(sid);
    setunits(units) ;
    setPrograms(Pro grams);

    }

    public void setLastName(Str ing lastName){
    lastName = lastName;
    }

    public String getLastName(){
    return lastName;
    }

    public void setFirstName(St ring firstName){
    firstName = firstName;
    }

    public String getFirstName(){
    return firstName;
    }

    public void setMiddleName(S tring middleName){
    middleName = middleName;
    }

    public String getMiddleName() {
    return middleName;
    }

    public void setsid(int sid){
    sid = sid;
    }
    public int getsid(){
    return sid;
    }


    public void setunits(double units){
    units = units;
    }


    public double getunits()
    {
    return units;
    }


    public void setPrograms(Str ing Programs){
    Programs = Programs;
    }

    public String getPrograms(){
    return Programs;
    }

    }

    ]
    Another class
    [

    import java.io.File;
    import java.io.IOExcep tion;
    import java.util.Scann er;

    public class Roaster {

    Student st[] = new Student[100];

    /* public static void copyLines() throws IOException {
    BufferedReader inputStream = null;
    PrintWriter outputStream = null;

    try {
    inputStream =
    new BufferedReader( new FileReader("roa ster.txt"));

    for(i=0;i<no.of lines;i++)
    {
    addstudent(fir,
    }
    outputStream =
    new PrintWriter(new FileWriter("cha racteroutput.tx t"));

    String l;
    while ((l = inputStream.rea dLine()) != null) {

    outputStream.pr intln(l);
    }
    } finally {
    if (inputStream != null) {
    inputStream.clo se();
    }
    if (outputStream != null) {
    outputStream.cl ose();
    }
    }
    }*/

    public void addStudentfromF ile() throws IOException
    {
    Scanner inputStream = null;
    try {
    inputStream =
    new Scanner(new File("roaster.t xt"));
    int noofstu = 1;

    while (inputStream.ha sNext()) {

    String temp = inputStream.nex t();
    String[] name = null;
    name = temp.split(",") ;
    /* System.out.prin tln(name[0]);
    System.out.prin tln(name[1]);
    System.out.prin tln(inputStream .next());

    System.out.prin tln(inputStream .nextInt());

    System.out.prin tln(inputStream .nextDouble());
    System.out.prin tln(inputStream .next());*/
    st[noofstu-1] = new Student(name[0], name[1], inputStream.nex t(),inputStream .nextInt() , inputStream.nex tDouble(),input Stream.next());
    noofstu++;
    }
    } finally {
    if (inputStream != null) {
    inputStream.clo se();
    }

    }

    }

    public int getStudentno(){
    //getStudent = new Student;
    return st.length;

    }


    public static void main(String[] args) {


    }
    }
    ]
    Another class for testing
    [
    import java.io.Buffere dInputStream;
    import java.io.Buffere dReader;
    import java.io.DataInp utStream;
    import java.io.File;
    import java.io.FileInp utStream;
    import java.io.FileRea der;
    import java.io.IOExcep tion;

    public class RoasterTest {

    public static void main (String[] args) throws Exception{
    File RoasterTest = new File( "roaster.tx t" );
    if ( RoasterTest.exi sts() )
    {
    // Create the buffered reader for reading the file
    BufferedReader inFile = new BufferedReader( new FileReader( RoasterTest ) );



    // Get the first line of the file
    String line = inFile.readLine ();

    // If line is not end of file continue
    while ( line != null )
    {
    // Create a StringTokenizer with a colon sign as a delimiter
    java.util.Strin gTokenizer st =
    new java.util.Strin gTokenizer( line, ":" );

    // Display the content of the first token
    System.out.prin t( " Name: " + st.nextToken() );

    // Display the total number of tokens remaining this string
    int numScores = st.countTokens( );

    // Initialize the sum to zero
    int sum = 0;

    // Get each score, add it to the sum and print it
    for ( int i=1; i <= numScores; i++ )
    {
    int score = Integer.parseIn t( st.nextToken() );
    sum += score;
    }

    // Display the average score for this student
    System.out.prin tln( " average = " + sum/numScores );

    // Read next line of the file
    line = inFile.readLine ();

    } // end while not at end of file

    // Close the BufferedReader
    inFile.close();

    // try {
    // RoasterTest.clo ne();
    // } catch (IOException ioe) {

    } // end if the grade file doesn't exist

    }

    }

    ]

    My test class does not read student class or roaster class .. I know I am missing something but I am loss
    Use Code Tags.
    Please post the file content.

    Debasis Jana

    Comment

    • Jromero
      New Member
      • Sep 2007
      • 16

      #3
      My code
      [

      public class Student{
      private String lastName;
      private String firstName;
      private String middleName;
      private int sid;
      private double units;
      private String Programs;


      public Student(){
      this( "", "", "", 0, 0.0, "");
      }

      public Student (String lastName, String firstName, String middleName, int sid, double units, String Programs )
      {
      //setLastName(las tName);
      setFirstName(fi rstName);
      setMiddleName(m iddleName);
      setsid(sid);
      setunits(units) ;
      setPrograms(Pro grams);

      }

      public void setLastName(Str ing lastName){
      lastName = lastName;
      }

      public String getLastName(){
      return lastName;
      }

      public void setFirstName(St ring firstName){
      firstName = firstName;
      }

      public String getFirstName(){
      return firstName;
      }

      public void setMiddleName(S tring middleName){
      middleName = middleName;
      }

      public String getMiddleName() {
      return middleName;
      }

      public void setsid(int sid){
      sid = sid;
      }
      public int getsid(){
      return sid;
      }


      public void setunits(double units){
      units = units;
      }


      public double getunits()
      {
      return units;
      }


      public void setPrograms(Str ing Programs){
      Programs = Programs;
      }

      public String getPrograms(){
      return Programs;
      }

      }

      ]
      Another class
      [

      import java.io.File;
      import java.io.IOExcep tion;
      import java.util.Scann er;

      public class Roaster {

      Student st[] = new Student[100];

      /* public static void copyLines() throws IOException {
      BufferedReader inputStream = null;
      PrintWriter outputStream = null;

      try {
      inputStream =
      new BufferedReader( new FileReader("roa ster.txt"));

      for(i=0;i<no.of lines;i++)
      {
      addstudent(fir,
      }
      outputStream =
      new PrintWriter(new FileWriter("cha racteroutput.tx t"));

      String l;
      while ((l = inputStream.rea dLine()) != null) {

      outputStream.pr intln(l);
      }
      } finally {
      if (inputStream != null) {
      inputStream.clo se();
      }
      if (outputStream != null) {
      outputStream.cl ose();
      }
      }
      }*/

      public void addStudentfromF ile() throws IOException
      {
      Scanner inputStream = null;
      try {
      inputStream =
      new Scanner(new File("roaster.t xt"));
      int noofstu = 1;

      while (inputStream.ha sNext()) {

      String temp = inputStream.nex t();
      String[] name = null;
      name = temp.split(",") ;
      /* System.out.prin tln(name[0]);
      System.out.prin tln(name[1]);
      System.out.prin tln(inputStream .next());

      System.out.prin tln(inputStream .nextInt());

      System.out.prin tln(inputStream .nextDouble());
      System.out.prin tln(inputStream .next());*/
      st[noofstu-1] = new Student(name[0], name[1], inputStream.nex t(),inputStream .nextInt() , inputStream.nex tDouble(),input Stream.next());
      noofstu++;
      }
      } finally {
      if (inputStream != null) {
      inputStream.clo se();
      }

      }

      }

      public int getStudentno(){
      //getStudent = new Student;
      return st.length;

      }


      public static void main(String[] args) {


      }
      }

      import java.io.Buffere dInputStream;
      import java.io.Buffere dReader;
      import java.io.DataInp utStream;
      import java.io.File;
      import java.io.FileInp utStream;
      import java.io.FileRea der;
      import java.io.IOExcep tion;

      public class RoasterTest {

      public static void main (String[] args) throws Exception{
      File RoasterTest = new File( "roaster.tx t" );
      if ( RoasterTest.exi sts() )
      {
      // Create the buffered reader for reading the file
      BufferedReader inFile = new BufferedReader( new FileReader( RoasterTest ) );



      // Get the first line of the file
      String line = inFile.readLine ();

      // If line is not end of file continue
      while ( line != null )
      {
      // Create a StringTokenizer with a colon sign as a delimiter
      java.util.Strin gTokenizer st =
      new java.util.Strin gTokenizer( line, ":" );

      // Display the content of the first token
      System.out.prin t( " Name: " + st.nextToken() );

      // Display the total number of tokens remaining this string
      int numScores = st.countTokens( );

      // Initialize the sum to zero
      int sum = 0;

      // Get each score, add it to the sum and print it
      for ( int i=1; i <= numScores; i++ )
      {
      int score = Integer.parseIn t( st.nextToken() );
      sum += score;
      }

      // Display the average score for this student
      System.out.prin tln( " average = " + sum/numScores );

      // Read next line of the file
      line = inFile.readLine ();

      } // end while not at end of file

      // Close the BufferedReader
      inFile.close();

      // try {
      // RoasterTest.clo ne();
      // } catch (IOException ioe) {

      } // end if the grade file doesn't exist

      }

      }

      ]

      This is my code

      Comment

      • dmjpro
        Top Contributor
        • Jan 2007
        • 2476

        #4
        Look, have look at "ObjectInputStr eam","ObjectOut putStream" and "Serializat ion" in java.
        Have a look through Google.
        Any further problem, please post here.

        Debasis Jana

        Comment

        • Jromero
          New Member
          • Sep 2007
          • 16

          #5
          I still don't get it please help me

          Comment

          • dmjpro
            Top Contributor
            • Jan 2007
            • 2476

            #6
            Originally posted by Jromero
            I still don't get it please help me
            Look,
            "ObjectInputStr eam" for object reading from a stream,
            and "ObjectOutputSt ream" for object writing for a strean.
            Now the Object should implement "Serializab le" interface.

            Have a look at this sample code ...............

            [code=java]
            ObjectOutputStr eam o = new OutjectOutputSt ream(new FileOutputStrea m("test.dat") );
            Student s = new Student(/*Some data goes here*/);
            o.writeObject(s );
            .
            .
            ObjectInputStre am i = new ObjectInputStre am(new FileInputStream ("test.dat") );
            Student _s = (Student)i.read Object();
            //now access the _s object.
            [/code]

            Your Student class should be like this .......
            [code=java]
            class Student implements Serializable
            {
            //your code goes here
            }
            [/code]

            Debasis Jana

            Comment

            • Jromero
              New Member
              • Sep 2007
              • 16

              #7
              The
              Code[
              ObjectOutputStr eam o = new ObjectOutputStr eam(new FileOutputStrea m("roaster.txt" ));
              Student s = new Student("String lastName, String firstName, String middleName, int sid, double units, String Programs", null, null, 0, 0, null);
              o.writeObject(s );

              ObjectInputStre am i = new ObjectInputStre am(new FileInputStream ("roaster.txt") );
              Student _s = (Student)i.read Object();
              // now access the _s object.

              ]
              Goes in Roaster class

              Comment

              • dmjpro
                Top Contributor
                • Jan 2007
                • 2476

                #8
                You got your code worked?

                Actually I forgot to close the streams.
                See the code carefully.
                [code=java]
                ObjectOutputStr eam o = new OutjectOutputSt ream(new FileOutputStrea m("test.dat") );
                Student s = new Student(/*Some data goes here*/);
                o.writeObject(s );
                o.close();
                .
                .
                ObjectInputStre am i = new ObjectInputStre am(new FileInputStream ("test.dat") );
                Student _s = (Student)i.read Object();
                i.close();
                //now access the _s object.
                [/code]

                Your Student class should be like this .......
                [code=java]
                class Student implements Serializable
                {
                //your code goes here
                }
                [/code]


                Debasis Jana

                Comment

                • Jromero
                  New Member
                  • Sep 2007
                  • 16

                  #9
                  I am still having problems I don't where to put the object stream

                  Comment

                  Working...