Go Back   CodingForums.com > :: Computing & Sciences > Computer Programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-14-2005, 12:01 PM   PM User | #1
conafam
New Coder

 
Join Date: Mar 2004
Posts: 13
Thanks: 0
Thanked 0 Times in 0 Posts
conafam is an unknown quantity at this point
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
conafam is offline   Reply With Quote
Old 02-14-2005, 04:00 PM   PM User | #2
smeagol
Regular Coder

 
Join Date: Jul 2002
Location: Kentucky
Posts: 132
Thanks: 0
Thanked 0 Times in 0 Posts
smeagol is an unknown quantity at this point
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();
}
}
__________________
Kevin
Kevin Adams | Compiled Code
smeagol is offline   Reply With Quote
Old 02-15-2005, 10:01 AM   PM User | #3
conafam
New Coder

 
Join Date: Mar 2004
Posts: 13
Thanks: 0
Thanked 0 Times in 0 Posts
conafam is an unknown quantity at this point
Thank you Kevin/Smeagol - that's great!

Much appreciated.
conafam is offline   Reply With Quote
Old 02-15-2005, 03:39 PM   PM User | #4
cfc
Regular Coder

 
Join Date: Dec 2004
Location: Keswick, Ontario
Posts: 251
Thanks: 0
Thanked 0 Times in 0 Posts
cfc is an unknown quantity at this point
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
    }
  }
} ///:~
cfc is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:10 PM.


Advertisement
Log in to turn off these ads.