Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    abetemari is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default problem with FileReader and FileWriter

    Hello All!
    I am having a little(may be big) problem with the writing to and reading from a file. The readInfo method is supposed to read from a file and store the info in an ArrayList, and the writeInfo method is supposed to write the info from an ArrayList onto a file. Your help highly appreciated. I'm running out of time.:(

    Java Code:
    public static void readInfo() throws IOException
        {
             //read books from file to arrayList
             File booksFile = null ;
             String FIELD_SEP = "\t";
             BufferedReader in = null;
    
             try
             {
                in = new BufferedReader(new FileReader(booksFile));
                ArrayList books = new ArrayList<Book>();
    
                // read all products stored in the file
                // into the array list
                String line = in.readLine();
                while(line != null)
                {
                    String[] columns = line.split(FIELD_SEP);
                    String isbn = columns[0];
                    String title = columns[1];
                    String price = columns[2];
                    String quantity = columns[3];
    
                    Book b = new Book(
                        isbn, title, Double.parseDouble(price), Integer.parseInt(quantity));
                    books.add(b);
    
                    line = in.readLine();
                }
    
            }
             catch(IOException ioe)
             {
                 ioe.printStackTrace();
            }
        }
    
     public static void writeInfo() throws IOException
     {
            ArrayList<Book> books = new ArrayList<Book>();
            File booksFile = null ;
            String FIELD_SEP = "\t";
    
             //write books into the file from the arrayList
    
              // open output stream for overwriting
                PrintWriter out = null;
                out = new PrintWriter(
                new BufferedWriter(
                new FileWriter(booksFile)));
    
                // write all products in the array list
                // to the file
                for (Book b : books)
                {
                    out.print(b.getISBN() + FIELD_SEP);
                    out.print(b.getTitle() + FIELD_SEP);
                    out.println(b.getPrice());
                    out.println(b.getQuantity());
                }
         }

  2. #2
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    Quote Originally Posted by abetemari View Post
    Hello All!
    I am having a little(may be big) problem with the writing to and reading from a file. The readInfo method is supposed to read from a file and store the info in an ArrayList, and the writeInfo method is supposed to write the info from an ArrayList onto a file. Your help highly appreciated. I'm running out of time.:(

    Java Code:
    public static void readInfo() throws IOException
        {
             //read books from file to arrayList
             File booksFile = null ;
             String FIELD_SEP = "\t";
             BufferedReader in = null;
    
             try
             {
                in = new BufferedReader(new FileReader(booksFile));
                ArrayList books = new ArrayList<Book>();
    
                // read all products stored in the file
                // into the array list
                String line = in.readLine();
                while(line != null)
                {
                    String[] columns = line.split(FIELD_SEP);
                    String isbn = columns[0];
                    String title = columns[1];
                    String price = columns[2];
                    String quantity = columns[3];
    
                    Book b = new Book(
                        isbn, title, Double.parseDouble(price), Integer.parseInt(quantity));
                    books.add(b);
    
                    line = in.readLine();
                }
    
            }
             catch(IOException ioe)
             {
                 ioe.printStackTrace();
            }
        }
    
     public static void writeInfo() throws IOException
     {
            ArrayList<Book> books = new ArrayList<Book>();
            File booksFile = null ;
            String FIELD_SEP = "\t";
    
             //write books into the file from the arrayList
    
              // open output stream for overwriting
                PrintWriter out = null;
                out = new PrintWriter(
                new BufferedWriter(
                new FileWriter(booksFile)));
    
                // write all products in the array list
                // to the file
                for (Book b : books)
                {
                    out.print(b.getISBN() + FIELD_SEP);
                    out.print(b.getTitle() + FIELD_SEP);
                    out.println(b.getPrice());
                    out.println(b.getQuantity());
                }
         }
    1. Try not to initialize variables in the body of methods or in the body of loops.

    2. Your booksFile variable is null and never defined for the BufferedReader or BufferedWriter.

    3. A FileReader is unnecessary for a BufferedReader, you can just define it like this:
    Java Code:
    in = new BufferedReader(booksFile);
    4. Your while loop could be done better like so:
    Java Code:
    String line;
    while((line=in.readLine()) != null){
    /* your code */
    }
    5. A FileWriter and PrintWriter for your BufferedWriter is unneeded, pick one or the other. PrintWriter is best for text files.

    You're also highly overcomplicating the creation of a BufferedWriter. The BufferedWriter is what you're writing with; not a PrintWriter. So, your "out" should be a BufferedWriter, not a PrintWriter. So, simply change "out"'s initialization from PrintWriter to BufferedWriter and define your BufferedWriter like so:
    Java Code:
    out = new BufferedWriter(new PrintWriter(booksFile));
    ____________________________________

    That should fix your problems from what I see. If there's any more errors or problems, please post the specific errors or problems with detail.
    Last edited by Solarsonic; 03-27-2011 at 10:29 PM.

  3. #3
    UJJAL DHAR is offline Senior Member
    Join Date
    Apr 2010
    Location
    Dhaka,Bangladesh
    Posts
    180
    Rep Power
    0

    Default

    If your problem is in methods,then I am posting a sample code.Remember, this code may be not well formated but is error free..

    Java Code:
    import java.io.*;
    
    
    
    class ReadFile{
    
    
        String temp,stable;
    
    public ReadFile(){
    /////reading from file///////////////
    try{
        String filename="D:/filename.txt";
    BufferedReader user = new BufferedReader (new FileReader (filename));
    
      stable="";
    while((temp=user.readLine())!=null){
        stable+=temp;
    //every line of your file is in temp each time
    //write your code here
    }
    
    //////writing to a new file///////////////
               FileWriter fm = new FileWriter("D:/filename2.txt");
               BufferedWriter out = new BufferedWriter(fm);
              out.write(stable);
              out.close();
    
    }
    catch(Exception e){}
    
    }//end of constructor ReadFile
    
    };
    //end of constructor ReadFile
    
    
    
    
    public class file {
    
      public static void main(String a[]){
    
      ReadFile file=new ReadFile();
    
    
      }
    
    
    }

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Solarsonic View Post
    1. Never initialize variables in the body of methods or in the body of loops.
    Could you please clarify what you mean by this statement as it's awfully broad and I'm not sure that I agree with it fully.

  5. #5
    UJJAL DHAR is offline Senior Member
    Join Date
    Apr 2010
    Location
    Dhaka,Bangladesh
    Posts
    180
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Could you please clarify what you mean by this statement as it's awfully broad and I'm not sure that I agree with it fully.
    I think he said this because every time the loop/method starts,the variable initializes also if they are in the body of that loop.

  6. #6
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    Quote Originally Posted by Fubarable View Post
    Could you please clarify what you mean by this statement as it's awfully broad and I'm not sure that I agree with it fully.
    What's the point of initializing a variable over and over again in a loop when you can just initialize it once outside the loop?

    Same way with methods (when you use a method over and over again).

    So I could say try not to.

  7. #7
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Never is too large of a blanket statement, while it may not always be good to perform declarations in loops and method body, there are plenty of times where the local variable comes in handy.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by sunde887 View Post
    Never is too large of a blanket statement, while it may not always be good to perform declarations in loops and method body, there are plenty of times where the local variable comes in handy.
    I like this article on how to write Java code that performs well: Brian Goetz Interview: Write Dumb Code

    Part of the interview states this:
    The answer may seem counterintuitive. Often, the way to write fast code in Java applications is to write dumb code -- code that is straightforward, clean, and follows the most obvious object-oriented principles. This has to do with the nature of dynamic compilers, which are big pattern-matching engines. Because compilers are written by humans who have schedules and time budgets, the compiler developers focus their efforts on the most common code patterns, because that's where they get the most leverage. So if you write code using straightforward object-oriented principles, you'll get better compiler optimization than if you write gnarly, hacked-up, bit-banging code that looks really clever but that the compiler can't optimize effectively.

    So clean, dumb code often runs faster than really clever code, contrary to what developing in C might have taught us. In C, clever source code turns into the expected idiom at the machine-code level, but it doesn't work that way in Java applications. I'm not saying that the Java compiler is too dumb to translate clever code into the appropriate machine code. It actually optimizes Java code more effectively than does C.

  9. #9
    abetemari is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default

    I tried to initialize the bookFile and the arrayList at the beginning and use an instance variable in a method I get the error message: "non-static variable booksFile cannot be referenced from a static context". That is why I was initializing them in every method. just for clarity and so you can see the whole thing, here is the code:

    Java Code:
    [CODE]import java.io.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.text.JTextComponent;
    import java.text.*;
    
    public class MyMethods
    {
        private File booksFile = null;
        public ArrayList<Book> books;
        private final String FIELD_SEP = "\t";
        MyMethods()
        {
    
        }
    
        public static void addNewBook()
        {
                    //get input
                    Book newBook = new Book();
    		String  isbn = "", title = ""; 
    		double price = 0;
    		int quantity = 0;
                    //private ArrayList<Book> book
    		            
    		newBook.setISBN(isbn);
    		newBook.setTitle(title);
    		newBook.setPrice(price);
    		newBook.setQuantity(quantity);
    
                    // if the file doesn't exist, create it
                    try
                    {
                        File booksFile;
                        booksFile = new File("catalog.text");
                        if (!booksFile.exists())
    			booksFile.createNewFile();
                    }
                    catch(IOException ioe)
                    {
                        ioe.printStackTrace();
                    }
                    ArrayList<Book> books = new ArrayList<Book>();  
                    books.add(newBook);     
    				
    	}
        public static void readInfo() throws IOException
        {
             //read books from file to arrayList
            // File booksFile = null ;
             String FIELD_SEP = "\t";
             BufferedReader in = null;
    
             try
             {
                in = new BufferedReader (booksFile);
                ArrayList books = new ArrayList<Book>();
    
                // read all products stored in the file
                // into the array list
                String line = in.readLine();
                while(line != null)
                {
                    String[] columns = line.split(FIELD_SEP);
                    String isbn = columns[0];
                    String title = columns[1];
                    String price = columns[2];
                    String quantity = columns[3];
    
                    Book b = new Book(
                        isbn, title, Double.parseDouble(price), Integer.parseInt(quantity));
                    books.add(b);
    
                    line = in.readLine();
                }
    
            }
             catch(IOException ioe)
             {
                 ioe.printStackTrace();
            }
        }
    
         public static void writeInfo() throws IOException
        {
            ArrayList<Book> books = new ArrayList<Book>();
            File booksFile = null ;
            String FIELD_SEP = "\t";
    
             //write books into the file from the arrayList
    
              // open output stream for overwriting
                PrintWriter out = null;
                out = new BufferedWriter(booksFile);
    
                // write all products in the array list
                // to the file
                for (Book b : books)
                {
                    if(Book bk !)
                    out.print(b.getISBN() + FIELD_SEP);
                    out.print(b.getTitle() + FIELD_SEP);
                    out.println(b.getPrice());
                    out.println(b.getQuantity());
                }
         }
         public static Book getBook() throws IOException
        {
             String bookISBN = "";
             String bookTitle = "";
             Book book1 = new Book();
             ArrayList<Book> books = new ArrayList<Book>();
    
             readInfo();
    
             if ((bookISBN.length() == 0)&& (bookTitle.length()== 0))
             {
                 JOptionPane.showMessageDialog(null, "Either BookTitle "
                                        + "or ISBN code is required",
                                        "Invalid Entry", JOptionPane.ERROR_MESSAGE);
                                //isbnTextField.requestFocusInWindow();
            }
            else if((bookISBN.length() != 0))
            {
                for(Book book: books)
                    if(bookISBN == book.getISBN())
                        book1 = book;
                    else
                        book1 = null;
            }
            else if((bookISBN.length() == 0) && bookTitle.length() != 0)
            {
                 for(Book book: books)
                    if(bookTitle == book.getTitle())
                        book1 = book;
                    else
                        book1 = null;
            }
    
    
             return book1;
        }
    
    
     }
    [/CODE]

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Java Code:
     {
                        File booksFile;
                        booksFile = new File("catalog.text");
                        if (!booksFile.exists())
    			booksFile.createNewFile();
                    }
    Is a problem, when you declare a variable as an instance variable, you can assign it directly.

    In other works, you can remove the line which says
    Java Code:
    File booksFile;
    booksFile was declared as an instance variable so you can instantiate it with the file directly.

  12. #12
    abetemari is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    All of your methods are static -- why?
    No reason! I am not sure when not to use static..

  13. #13
    abetemari is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    Java Code:
     {
                        File booksFile;
                        booksFile = new File("catalog.text");
                        if (!booksFile.exists())
    			booksFile.createNewFile();
                    }
    Is a problem, when you declare a variable as an instance variable, you can assign it directly.

    In other works, you can remove the line which says
    Java Code:
    File booksFile;
    booksFile was declared as an instance variable so you can instantiate it with the file directly.
    I did what you said and the next three lines showed error: non-static variable booksFile cannot be referenced from a static context

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by abetemari View Post
    No reason! I am not sure when not to use static..
    Then the rule of thumb is don't do it -- don't use static methods or variables unless you have a good reason to do so and know why you're doing it. This is causing one of your problems, the error message you've posted above. There are lots of other problems in your code including redeclaring variables in methods that are declared in the class, and I wonder if you should review a basics tutorial or two before moving forward with this project.

  15. #15
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    Quote Originally Posted by abetemari View Post
    I did what you said and the next three lines showed error: non-static variable booksFile cannot be referenced from a static context
    Take the static label off of your methods.

  16. #16
    abetemari is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default

    Quote Originally Posted by Solarsonic View Post
    Take the static label off of your methods.
    When the static label is taken off, I get a message at the place where i call the methods that says: non-static method getBook() cannot be referenced from a static context

  17. #17
    abetemari is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default MyMethods constructor

    Do you think there should be something in the MyMethods constructor?

  18. #18
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I really suggest you check out some tutorials. Get a stronger understanding of the basics.

  19. #19
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    Quote Originally Posted by abetemari View Post
    When the static label is taken off, I get a message at the place where i call the methods that says: non-static method getBook() cannot be referenced from a static context
    Ok so basically this is what you're gonna do. You're going to make the methods static and take the objects you need as parameters (BufferedReader, BufferedWriter, etc.).

  20. #20
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    Quote Originally Posted by abetemari View Post
    Do you think there should be something in the MyMethods constructor?
    Doing that and creating an instance of MyMethods could be possible but what I posted above would be better for a class like this that only contains methods to referenced to.

Page 1 of 2 12 LastLast

Similar Threads

  1. New line in FileWriter
    By luc@$ in forum New To Java
    Replies: 3
    Last Post: 01-31-2011, 05:45 AM
  2. write to file with filereader/filewriter
    By LennyKosmos in forum New To Java
    Replies: 3
    Last Post: 10-27-2010, 09:12 PM
  3. problem regarding FileReader
    By mukeshpaliwal in forum New To Java
    Replies: 7
    Last Post: 10-01-2010, 04:15 PM
  4. issue with FileReader and FileWriter
    By Uma R in forum Advanced Java
    Replies: 6
    Last Post: 07-16-2010, 02:16 PM
  5. JAva Filewriter
    By tommyyyy in forum New To Java
    Replies: 1
    Last Post: 03-28-2009, 01:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •