Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing the input into seperate variable!

Status
Not open for further replies.

CaitlinC

IS-IT--Management
Oct 28, 2001
5
US
Hi all,
I have a file, let's call it "log.txt" with this format:

Source Destination Distance
1 2 2
1 4 5
2 4 1
and so on...

Questions are:
1. What is the Java syntax to open a file?
2. How does Java read the content of a file line by line?
3. For each line, how do I seperate these numbers and put it under variable names? For instance, reading line 1:
Source[0] = 1, Dest[0]=2, Dist[0] =2 and so on...
Thanks a lot advance.
-Cait
 
Mr/mrs cait,
You can use the following program for your purpose,its simple and hope you understand it save the below as Seperator.java and run

If you still have any problem let me know it.

**********************************


import java.io.*;
import java.util.*;



public class Seperator extends Object {

//Declaring the collecting variables
static int Source[]= new int[10];
static int Dest[]= new int[10];
static int Dist[]= new int[10];

//Variable to keep count of number lines in the file
static int linecount = 0;


public static void main(String[] args) {

//While using some methods of BufferedReader exceptions are
//to be caught so used general try catch block
try{

//Creating a stream to read the file
File file = new File("c:/log.txt");
FileReader filereader = new FileReader(file);
BufferedReader in = new BufferedReader(filereader);


String str = in.readLine();

while(str != null){

//Assuming the tab space as seperator in the line
//If use some other string or character replace (\t)
//In the below line with that
//Say ,if you use (;) as seperator between numbers in line
//it will be as follow
//StringTokenizer token = new StringTokenizer(str,";");
StringTokenizer token = new StringTokenizer(str,"\t");

while(token.hasMoreTokens()){
//In a single line we have three tokens so getting each of
//The tokens below in the required fields
Source[linecount] = Integer.parseInt(token.nextToken());
Dest[linecount] = Integer.parseInt(token.nextToken());
Dist[linecount] = Integer.parseInt(token.nextToken());
}

//Printing the line with required format
System.out.println("Source : " + Source[linecount] + " Destination : " + Dest[linecount]+ " Distance : " + Dist[linecount] );

//Incrementing the line count
linecount++;

//Reading the next lin
str = in.readLine();

}

}catch(Exception ee){
System.out.println("You have some error in reading file");
}

} //end of main method


} //End of class
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top