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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read data line by line from a text file?

Status
Not open for further replies.

ddddd

Programmer
Joined
Jan 10, 2002
Messages
11
Location
US
Hi,

Can you show me the best code to read the data in a txt file:
(note: '*' represents space(s) or/and tab(s), 'head11' represents string '1111' is int and '1.111' is
float)

head12 * head12 * head13 *head14
1111 * 1.111 * 1.222 * 1222
2111 * 2.111 * 2.222 * 2222
.........
head22 * head22 * head23 *head24
1111 * 1.111 * 1.222 * 1222
2111 * 2.111 * 2.222 * 2222
.........
 
Hi ,
Here is the code for reading the line data from ur txt file. i have given the delimiter as a blank space.. u can change it to tab and check this program. Hope this helps :).

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

public class TxtReader
{
public static void main(String[] args) throws Exception
{
File txtFile = new File("filepath.txt"); // give ur file name here.
FileReader fr = new FileReader(txtFile);
BufferedReader br = new BufferedReader(fr);
String strLine = br.readLine().trim();

while(strLine != null)
{

if(strLine.equals(""))
{
// if blank line
continue;
}
else
{
String[] strTokens = getTokenArray(strLine," ",false);
for(int i = 0 ; i < strTokens.length; i++)
{
System.out.println(strTokens);
}
}
strLine = br.readLine();
}
}

private static String[] getTokenArray(String strString, String strDelim, boolean bIncDelim)
{
String strTokens[];
StringTokenizer oStrTkn;
int iCount = 0;
if(strString == null || strString.length() == 0)
{
return null;
}
oStrTkn = new StringTokenizer(strString, strDelim, bIncDelim);
strTokens = new String[oStrTkn.countTokens()];
while(oStrTkn.hasMoreTokens())
{
strTokens[iCount] = oStrTkn.nextToken();
iCount++;
}
return strTokens;
}
}


regards,
Reddy316
 
Thanks a lot for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top