Solved

How to read from a file ?

Posted on 2004-04-04
9
182 Views
Last Modified: 2010-03-31
Could you please give me the source code for a program that reads data from a file.

Example - My data.txt contains this:

1     2     3     4     5
 
Now: I want to read each number, knowing that there is a white space in between each os them. Later on the program should print in the screen:
1
2
3
4
5

Can you please code this for me and post it ?

0
Comment
Question by:digi_mind
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
9 Comments
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 10751268
You need a BufferedReader to read the line of numbers. Then you need a StringTokenizer to split the numbers up into substrings. And finally, if you need the actual values of the numbers, they need to be parsed using the Integer class. School assignment?
0
 

Author Comment

by:digi_mind
ID: 10751293
Yes, actually is a program that I have to make for school, but the main topic is not java, but c++.

Can you code it for me ?
0
 
LVL 30

Expert Comment

by:GrandSchtroumpf
ID: 10751316
if it's for school we cannot provide you with code.
post the code you have written so far and we can guide you.
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:digi_mind
ID: 10751386
This is what I have:
******************
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Random;
import java.util.StringTokenizer;

public class WriteText {
    /**     * Constructor for WriteText.     */    
   public WriteText() {        
      super();    
   }    
   
   public static void main(String[] args) {            
     
      String SEP = " ";      
      String FILENAME = "data.txt";                
     
      try {                                  
       StringTokenizer st = null;                  
       BufferedReader reader = new BufferedReader(new FileReader(FILENAME));                  
       String s = null;                  
       String[][] myArray = new String[1][6];                  
       int col;                  
       int row;                  
       String element = null;            
      
       while ((s = reader.readLine()) != null ) {                  
          st = new StringTokenizer(s,SEP);                  
            element = st;          
       }            
       System.out.println("VALUE : " + element );    
       reader.close();      
      }catch(Exception fe) {                  
         fe.printStackTrace(System.out);            
      }    
   }
}
**********************************************
My data.txt file contains 7 strings:
one two three four five six seven

I would like to have this strings in an array, then print in the screen position 4 of the array, so I will print:

four

Give me a hand, I am almost there...

0
 

Author Comment

by:digi_mind
ID: 10751403
My new code and better:
************************
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Random;
import java.util.StringTokenizer;

public class WriteText {
    /**     * Constructor for WriteText.     */    
   public WriteText() {        
      super();    
   }    
   
   public static void main(String[] args) {            
     
      String SEP = " ";      
      String FILENAME = "data.txt";                
     
      try {                                
      
       StringTokenizer st = null;                  
       BufferedReader reader = new BufferedReader(new FileReader(FILENAME));                  
       String s = null;                  
       String[] myArray = new String[3];                  
       int col = 0;                  
       String element = null;            
      
       while ((s = reader.readLine()) != null ) {                  
          st = new StringTokenizer(s,SEP);                  
            element = (String) st.nextElement();
          myArray[col] = element;
          col = col + 1 ;          
       }            
       System.out.println("VALUE : " + myArray[0] );    
       reader.close();      
      }catch(Exception fe) {                  
         fe.printStackTrace(System.out);            
      }  
   }
}
**************************************************

The problem is that when I print myArray[1] I get a value of null... and when I print myArray[0] I get "one" so the first value works...

i need to be able to store the other values in my array .

How ?
0
 
LVL 30

Accepted Solution

by:
GrandSchtroumpf earned 55 total points
ID: 10751435
>      while ((s = reader.readLine()) != null ) {                  
>         st = new StringTokenizer(s,SEP);                  
>            element = st;          
>      }            

here, you read each line of the file
and create a new StringTokenizer for each line.
what you probably want to do is to read the first line only.
or maybe read each line and test if the line is empty.  if the line is not empty, you create your StringTokenizer, otherwise you read the next line.
Once you have created your StringTokenizer, you should loop on the "Enumeration" (StringTokenizer implements Enumeration) and copy the values into your Array.

another method you could use is the split() method of String that returns a String[], but it might be a little complicated because it uses regular expressions.  continue with StringTokenizer for now.
0
 
LVL 30

Expert Comment

by:GrandSchtroumpf
ID: 10751443
you need to loop on your enumeration (while loop):
use  <  st.hasMoreElements();  >  to test if you have more elements.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Delete Android all or certain applications data programmatically 9 153
pagenation logic how it is working in my code 1 82
printf performancy 11 106
Java array 10 89
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question