Read a line of text in DataInputStream
HI,
I have a file with different data types, including text, with'\n' charater, integer and long, How could I read a line of text using DataInputStream?
DataInputStream is for reading primitives, but I came up with a (untested) workaround:
DataInputStream dis = new DataInputStream(new FileReader("bleh"));
StringBuffer s = new StringBuffer();
char c;
while((c = dis.readChar()) != '\n') {
s.append(c);
String line = s.toString();
StringBuffer is used because it gives better performance than String.
NOTE: I have NOT tested this.
Similar Messages
-
Reading Individual Lines of Text Into An ArrayList or Vector From A File
I am trying to read each individual line of text of a .txt file into an ArrayList or Vector. I seem to get the same results no matter which Object I am using (ArrayList or Vector). The text file is a comma-delimited text file to be used as a database. I want to separate each line as an individual record then dump it into an ArrayList or Vector and have them loop through a StringTokenizer() class so that I can be sure each line has the correct number of fields before I commit it to a serialization file. Currently, the proper amount of records seems to be forming in the initial part of the program, I am just remiss at properly placing them in the Vector, or StringTokenizer classes so I can further manipulate them. I'm using the LineNumberReader class to get line numbers to use as record numbers and for loop indexes. I'm not sure (obviously) if this is a correct way to do it or not.
Any help is greatly appreciated in advance.
Thanks for all your time.
int n = 0;
try {
* read each individual line and count it as a separate record.
* place each record into an array or may be a string if it has 9 tokens
* if a record hasn't got 9 tokens, it isn't a record
* place each array or string into a Vector
in = new LineNumberReader(new FileReader(filename));
while ((record = in.readLine()) != null) {
n = in.getLineNumber();
rawData = new Vector();
for (int i = 0; i < n; i++) {
rawData.add(record);
if (record == null)
break;
*The following System.out.println() statement shows that all lines are correctly retrieved from the text file
*as separate records
System.out.println("Record No. " + n + "= " + record);
//Debug
/** When these print lines execute it reveals that only the last record has been inserted into the Vector as
* many times as I have records in the text file.
System.out.println("Number of Records = " + n);
System.out.println("VectorSize = " + rawData.size());
System.out.println("First rawDataElement = " + rawData.firstElement());
System.out.println("Second rawDataElement = " + rawData.get(1));
System.out.println("Third rawDataElement = " + rawData.get(2));
System.out.println("Fourth rawDataElement = " + rawData.lastElement());
* Next run each record through a StringTokenizer to be sure that there the correct number of fields present
* If it contains the correct number of fields, dump it into an alternate ArrayList or Vector.
* As it is now, the StringTokenizer gives a NullPointerException
for (int i = 0; i < n; i++) {
StringTokenizer recordSet = new StringTokenizer((String) table.get(n), ",");
while (recordSet.hasMoreTokens()) {
if (recordSet.countTokens() == 9) {
data = new Vector();
data.add((Object) recordSet.nextToken(","));
System.out.println("Vector data size = " + data.size());
System.out.println("Second dataElement = " + data.get(0));
System.out.println("String Tok recordSet = " + recordSet.countTokens()); System.out.println("Number of Records = " + n);
System.out.println("First dataElement = " + data.firstElement());
System.out.println("Second dataElement = " + data.get(0));
System.out.println("Third dataElement = " + data.get(2));
System.out.println("Fourth dataElement = " + data.lastElement());
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}I think your logic is broken.
rawData = new Vector();
creates a new instance of Vector for every record.
Your add() within a for loop adds the same record to the Vector n times. I think what you really want is something like this:in = new LineNumberReader(new FileReader(filename));
rawData = new Vector();
while ((record = in.readLine()) != null) {
n = in.getLineNumber();
rawData.add(record); Mark -
How to read long line from text file
Hi,
I just faced problem when reading a big text file.
BufferedReader br = new BufferedReader(new FileReader("D:\\afile.txt"));
String str;
int i;
while ((str = br.readLine())!=null)
i++;
//do some work here...
...This code throws exception:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceSo I thought file line is very long. When I opened it in FAR it only displays no more than 4096 characters as a line.
Help me to read a text file that's line is very long?try,
$ java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xrunhprof[:help]|[:<option>=<value>, ...]
perform JVMPI heap, cpu, or monitor profiling
-Xdebug enable remote debugging
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
The -X options are non-standard and subject to change without notice. -
Reading first word from text file
Hello all,
I created a program which I can type in a line and store it into a file. What I need my next program to do is read and display just the first word from each line on the text file.
Here is what I have:
import java.io.*;
public class ReadFromFile
public static void main (String args[])
FileInputStream firstWord;
try
// Open an input stream
firstWord = new FileInputStream ("FileofWords.txt");
// Read a line of text
System.out.println( new DataInputStream(firstWord).readLine() );
// Close our input stream
firstWord.close();
System.err.println ("Unable to read from file");
System.exit(-1);
}what i would like is my program to get the first word of every line and put it in my array.
This is what i have attempted.
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class testing {
String[] tmp = new String [2];
String str;
public void programTest()
try
BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
while ((str = in2.readLine()) != null)
tmp = str.split(" ");
System.out.println(tmp[0]);
catch(IOException e)
System.out.println("cannot read file");
public static void main(String[] args)
testing B = new testing();
B.programTest();
}//end classAny help is most appreciated -
How to handle multiple threads to read one line from a file each time?
Dear Sir or Madam,
I'm new to multiple threads java programming. What I want to do is as following:
1. I'm writing a program to read one line of text from a very large file, and then do some process on this one line of text, then read the next line of text from this file, then process on this line of text, ...... When reach the end of the file, close the file.
This is a single thread scenario.
2. To fullly untilized computer resource, I want to create multiple threads to process this large file.
One thing is very important is that each line of text in the large file has to be read sequentially. This means that the first line of text in the large file is read first, then the second line, then the third line ......
My question is that if I create multiple threads to process the same file, how can I make sure that different threads will read the line of text from the same file sequentially?
I don't have enough experience on java multiple threads programming, so it will be very appreaciated if you can help me on this as soon as you are available.
Thanks and regards,
Steven WuA better solutoin would be to have a single thread that reads each line an puts it into a queue, and then multiple threads reading from the queue to process these lines.
This will only be effective if the amount of processing to be done on each line is very large compared to how long it takes to read the line, or if you have more than one CPU on your machine. -
How do i read complete line from a text file in j2me?????
how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..
That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..
-
Reading one line from a text file into an array
i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
public static void readAndProcessData(FileInputStream stream){
InputStreamReader iStrReader = new InputStreamReader (stream);
BufferedReader reader = new BufferedReader (iStrReader);
String line = "";
try{
int i = 0;
while (line != null){
names[i] = reader.readLine();
score[i] = reader.readLine();
line = reader.readLine();
i++;
}catch (IOException e){
System.out.println("Error in file access");
this section calls it:
try{
FileInputStream stream = new FileInputStream("ISU.txt");
HighScore.readAndProcessData(stream);
stream.close();
names = HighScore.getNames();
scores = HighScore.getScores();
}catch(IOException e){
System.out.println("Error in accessing file." + e.toString());
it gives me an array index out of bounds erroroh wait I see it when I looked at the original quote.
They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens. -
Read data from a text file, one line at a time.
I need to read data from a text file, and display each line in a String Indicator on Front Panel. It displays each line, but I get Error 4, End Of Line, unless I enter an extra line of data in the file that I don't need. I tried Read From Text File.vi, made by Nat Instr, and it gave the same error.
The Read from Text File.vi reads data from a text file line by line until the user stops the VI manually with the Stop button on the front panel, or until an error (such as "Error 4, End of file") occurs. If an error occurs, the Simple Error Handler.vi pops up a dialog that tells you which error occurred.
The Read from Text File.vi uses a while loop, but if you knew how many lines you wanted to read, you could replace the while loop with a for loop set to read that many lines from the file.
If you need something more dynamic because the number of lines in your files vary, then you could change the code of the Read from Text File.vi to the expect "Error 4, End of file" and handle it appropriately. This would require unbundling the error cluster that comes fro
m the Read File function with the Unbundle By Name function, so that you can expose the individual error "status" and error "code" values stored in the cluster. If the value of the error "code" is 4, then you can change the error "status" from true to false, and you can rebundle the cluster with the Bundle by Name function. Setting the error "status" to false instructs the Simple Error Handler to ignore the error. Otherwise, pass the original error cluster to the Simple Error Handler.vi, so that you can see what the error is.
Of course, if you're not interested in what the errors are, you could just remove the Simple Error Handler.vi, but then you wouldn't see any error messages.
Best of Luck,
Dieter
Dieter Schweiss
Applications Engineer
National Instruments -
How to read every line from a text file???
How can i read every line from my text file ("eka.txt")
now it only reads the first line and prints it out.
What is wrong with this?
import java.io.*;
import java.util.*;
class Testi{
public static void main(String []args)throws IOException {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
File inputFile = new File ("eka.txt");
FileReader fis =new FileReader(inputFile);
BufferedReader bis = new BufferedReader(fis);
String test=bis.readLine();
String tmp= "";
while((bis.readLine().trim() != null)) {
int spacefound=0;
int l=test.indexOf(" ");
for(int i=0;i<test.length();i++){
char c=test.charAt(i);
if(c!=' ') tmp+=""+c;
if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
tmp+=""+c;
spacefound++;
if(tmp.length()==l) {
System.out.println(tmp);
tmp="";
spacefound=0;
if(tmp.length()<l){
for(int i=0;i<=(l-tmp.length());i++)
tmp+=""+' ';
System.out.println(tmp);Try this code, Hope it servers your purpose.
import java.io.*;
import java.util.*;
class Testi {
public static void main(String []args)throws IOException {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
File inputFile = new File ("Eka.txt");
FileReader fis =new FileReader(inputFile);
BufferedReader bis = new BufferedReader(fis);
String test=bis.readLine();
while(test != null) {
StringTokenizer st = new StringTokenizer(test," ");
while(st.hasMoreTokens())
System.out.println(st.nextToken());
test = bis.readLine();
}Sudha -
How to read some lines from a text file using java.
hi,
i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
we only want to read the file upto the first Occurrence of "TEXT" string.
How to do it ,,,
Kinldy give the code
Regards,
Sagar
this is the text file
dfgjdjj
sfjhjkd
ghjkdg
hjkdgh TEXT
ikeyt
ujt
jk
tyk TEXT
rukl
rHendawy wrote:
Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
Edited by: sabre150 on Apr 29, 2009 2:13 PM -
Having trouble reading specific lines from a text file and displaying them in a listbox
I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dll"
Below is the code from that form.
Option Strict On
Option Infer Off
Option Explicit On
Public Class frmInventoryReport
Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
Dim intTemp As Integer
intTemp = lineNumber
Return lines(lineNumber - 1)
lineNumber = intTemp
End Function
Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
End Class
Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it. Is there anything other than name and cage number that should be associated with each animal?
You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple. Here's a simple class example:
Public Class Animal
Public Property Name As String
Public Property Cage As String
Public Overrides Function ToString() As String
Return String.Format("{0} - {1}", Name, Cage)
End Function
End Class
With that you can use a routine like the following to loop through all of the files and read each one:
Dim animals As New List(Of Animal)
Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
Using reader As New System.IO.StreamReader(filePath)
Dim lineIndex As Integer = 0
Dim currentAnimal As New Animal
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
If lineIndex = 0 Then
currentAnimal.Name = line
ElseIf lineIndex = 22 Then
currentAnimal.Cage = line
Exit While
End If
lineIndex += 1
End While
animals.Add(currentAnimal)
End Using
Next
'do something to display the animals list
Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView. If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
There are lots of options depending on what you want and what all you need to do.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all" -
JSF - Read a text file and diplay lines of text data on the web page
Hello,
For one of my projects, I need to display lines of text data on the web page using Java Server Faces Technology. The raw data could be from simple text files or sockets or anything. (Getting the data is not my issue but displaying is). Could anybody send answers with sample code. In servlet, one could do this by -
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println(DATA);
out.println(DATA);
out.println("</html>");
I am looking for similar solution.
Thanks in advance
DKThanks mjolinor. Works great!
Two questions.
1. Could you plz suggest how this could be modified so this code would read the file in or accept it from the pipeline instead of wrapping the (@' around the data?
2. Could you plz briefly describe some of the details of the code so I can further research and understand.
Thanks for your help.
Thanks for your help! SdeDot
1. It already reads in the file. The (@' .. '@) bits are just there to create a file using your test data to demonstrate that it works.
2. Not user what kind of "details" you want. There really isn't much there, and get-help on the cmdlets used should provide information on what's going on with them in that script.
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " " -
Reading in a line of text and breaking it up, complicated
Hi all,
At the moment im reading in a few 100 lines of text from a file, each line contains a command and a few variables which need to be set to existing variables I have created shown below;
Int variableA ;
Int variable B ;
Int variable C;
Int Variable D;
However I have no way to know which command will go with which variables,
On every line there will be one command and two variables..
The possible command are; ADD, SUB, TIMES, Divide, COPY, SET
And the text coming in look like this;
SET A10, B15 // set each variable
SET C33, D50 // as above
COPY A, B // which means assign copy what ever in variableA to variableB
ADD C, D // which mean add variableC�s contents to variableD contents
SUB B, C // which is subtract variableC contents by what ever is in variableB
Does anybody know of a way where I can test what the next command is, and assign the correspond variables , so far I have come up with;
But am not sure if this is the best way to go about it, was thinking maybe I should put the text file into an array, which might make it easyer to process.
public static void main (String [] args)
int D = 0 ;
int C = 0 ;
int B = 0 ;
int A = 0 ;
StringTokenizer st ;
String line ;
String buffer = "";
String file ="test2.txt" ;
String name = "";
String billy = "";
try
FileReader fr = new FileReader(file) ;
BufferedReader inFile = new BufferedReader (fr) ;
//read in one line @ a time
buffer =inFile.readLine() ;
while (buffer !=null)
StringTokenizer words = new StringTokenizer (buffer) ;
//put the buffer "line" into a tokenizer for individual characters out of a line;
while(words.hasMoreTokens())
String letter = words.nextToken() ;
if(letter.charAt (0) == 'S') // if first letter = S would be SET
System.out.println(letter) ;
//display the token as a test output;
if(letter.charAt (0) == 'A') // if letter = A would be ADD
System.out.println(letter) ;
buffer = inFile.readLine() ;
//read in next line
inFile.close();
catch (FileNotFoundException e)
System.out.println("File not found");
catch ( IOException e)
System.out.println("IO Exception") ;
}hi,
i think that what u r tring to do is "parsing" where u translate these primatin=ve commands to execute them, if so here what u need to do:
Rad a line untell end of file
for each token in the line
if(token="SET" || token="ADD || token=""SUB")
{ //save operation for later use
operation=token;
//now u expect the next token to be an operand
token=nextToken;
if (token!="" and token!=",")//it must be an operand
{operand1=token;
token=next token;
if(token=",")//do nothing just read the nest operand
token=nexttoken;
else //syntax error in file, exit ;
if (token!="" and token!=",")//checking the 2nd operand
operand2=token;
//now check value of operation and call the right method and send operand1,operand2 as arguments to get the result e.g
if(opration=="ADD")
system.println("result of addition is"+addMethod(operand1,operand2));
hope that helps,
Insighter -
How to read line number text from PDF using plugin?
Hi, I would like to know how to read line number text from PDF using plugin?
Thanks in advance.Ok, some background reading of the PDF Reference will help you understand why this is so difficult. PDF files are not organised into lines. It is best to think of each word or character on the page as being a graphic with its own position. The human eye sees lines where a series of graphics (words) are roughly in the same horizontal region.
In the general case it is difficult or even impossible to answer this. You may have columns with different spacing (but the PDF stores no information on what is a column). You may have subscripts and superscripts. You may have text in graphics coinciding with other text. Commonly, there may be titles, headings or page numbers which are just ordinary text and might count as lines.
That said, what you need to do is extract the text on the page and its positions. The WordFinder APIs are the way to do that. Now, sort all the words out, using the Y coordinates and size to try and guess what makes a "line". Now you are in a position to find the text (divided into words, not strings) and report the "line number" you have estimated. -
Read lines from text file to java prog
how can I read lines from input file to java prog ?
I need to read from input text file, line after line
10x !If you search in THIS forum with e.g. read lines from file, you will find answers like this one:
Hi ! This is the answer for your query. This program prints as the output itself reading line by line.......
import java.io.*;
public class readfromfile
public static void main(String a[])
if you search in THIS forum, with e.g. read lines from text file
try{
BufferedReader br = new BufferedReader(new FileReader(new File("readfromfile.java")));
while(br.readLine() != null)
System.out.println(" line read :"+br.readLine());
}catch(Exception e)
e.printStackTrace();
}
Maybe you are looking for
-
Defined WSDL in ID is not accepted
Hello, i have created a wsdl by the wizzard define WS in the integration directory. the wsdl is working fine with xml spy an the soap sender adapter. but when we try to import the wsdl into the SAP NetWeaver Composition Environment we get the followi
-
Revision: 5465 Author: [email protected] Date: 2009-03-20 11:52:56 -0700 (Fri, 20 Mar 2009) Log Message: Now that padding set on a TextInput does not affect the inner textView, we need to add a custom TextInput skin for the TextInput a Spark NumericS
-
Address Book Images Gone Funky
Adding images to Address Book contacts just results in a random part of the image showing. In iOS I can add images just fine, and they show up in Address Book ok. It's never done this before. Any ideas??
-
Hey there folks. I have a bit of a problem. When I record video on my N95 it's fine if the camera is completely still but on panning shots the picture visibly 'wobbles' no matter how smoothly or steadily I move the camera. It does this both with and
-
(IPlanet 6 - SP4) we have something like this in the EntityBean : ejbstore() try { myDAO.Update(); catch(SQLException se) throw new EJBException(se); But in the SessionBean, where we set the detail (which causes ejbStore() to fire), I'm seeing a Tran