Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2004
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question How to read in text files?

    Hi,

    I need to be able to create a very simple Java program (not javascript) which reads in a text file and then outputs it's contents to the screen. Although it sounds very simple I am an extreme beginner and was looking for some help.

    The code I have just now is:
    Code:
    public class Tutorial1{
        
        private float[] data = new float[2000];
    
        //constructor
        public Tutorial1(){}
    
        /**
         *readData
         *input: String filename
         *store the values of the third column of numbers of the data file into the member array: data
         */
        public void readData(String filename){
    	...
        }
        
        //entry point
        public static void main(String args[]){
    	Tutorial1 tut1 = new Tutorial1();
    
    	//read data
    	tut1.readData("data.txt");
    	//print out content of data
    	....
    	    }
    }
    Where the "...." are I need to complete my own code but I have no idea. Can someone help?

    Much appreciated

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    Kentucky
    Posts
    133
    Thanks
    0
    Thanked 1 Time in 1 Post
    Here's an example of how to read in the contents of a text file. By the way, you were going to try to call the readData method from main, which can't happen without readData being static, too. I just called it from the constructor as you'll see:

    Hope this helps,
    Kevin


    import java.io.*;

    class Tutorial1
    {
    public Tutorial1()
    {
    this.readData("testfile.txt");
    }

    /**
    * readData
    * input String filename
    * store the values of the third column of numbers of the data file into the member array: data
    */
    public void readData(String filename)
    {
    try
    {
    File file = new File(filename);
    BufferedReader reader = new BufferedReader(new FileReader(file));

    String line = null;

    while((line = reader.readLine()) != null)
    {
    System.out.println(line);
    }
    }
    catch(FileNotFoundException ex)
    {
    System.out.println(ex.toString());
    }
    catch (IOException ex)
    {
    System.out.println(ex.toString());
    }
    }

    public static void main(String args[])
    {
    Tutorial1 tut1 = new Tutorial1();
    }
    }

  • #3
    New Coder
    Join Date
    Mar 2004
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you Kevin/Smeagol - that's great!

    Much appreciated.

  • #4
    cfc
    cfc is offline
    Regular Coder
    Join Date
    Dec 2004
    Location
    Keswick, Ontario
    Posts
    251
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Are you learning Java from online tutorials? If so, I sincerely recommend getting a book, esp. to begin with and get a solid background of the language. I've been promoting Bruce Eckel's Thinking in Java books since I originally picked Java up from the 2nd edition (when J2SDK1.3 was out), and I think they're the best free resources available for learning Java. They're available for free in downloadable form, but you can also buy them on paper or CD-ROM.

    http://www.mindview.net/Books/TIJ/ -- the 2nd edition was about a two week read (while doing other things of course), and I expect the third edition to take about as long to read.

    Also of interest if you're using Java 1.4+ will be the java.nio packages; they're more complex to use because they're lower-level, but that also makes the new I/O system more efficient. This example, which I borrowed from Thinking in Java, 3rd Edition by Bruce Eckel (see above) will copy one file to another using the new I/O system (bytebuffers and channels):
    Code:
    //: c12:ChannelCopy.java
    // Copying a file using channels and buffers
    // {Args: ChannelCopy.java test.txt}
    // {Clean: test.txt} 
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    
    public class ChannelCopy {
      private static final int BSIZE = 1024;
      public static void main(String[] args) throws Exception {
        if(args.length != 2) {
          System.out.println("arguments: sourcefile destfile");
          System.exit(1);
        }
        FileChannel 
          in = new FileInputStream(args[0]).getChannel(),
          out = new FileOutputStream(args[1]).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        while(in.read(buffer) != -1) {
          buffer.flip(); // Prepare for writing
          out.write(buffer);
          buffer.clear();  // Prepare for reading
        }
      }
    } ///:~


  •  

    Posting Permissions

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