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 error
oh 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.
Similar Messages
-
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 -
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 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..
-
Read specified line from a text file
Hi,
I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?
Thanks and regards,
Krt_MaltaKrt_malta wrote:
I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?Is there anything in your use case that precludes using the offset of the start of the line rather than the line number? -
How to read some records from a text file into java(not all records)
hello,
how to read text files into java. i need only few records from the text file not all records at a time.
If any one knows plz reply me
my id is [email protected]this snipet reads a text file line by line from line 1 to 3
try {
FileReader fr = new FileReader(directory);
BufferedReader br = new BufferedReader(fr);
int counter = 0;
while ((dbconn = br.readLine()) != null) {
switch(counter){
case 0:
status = dbconn;
break;
case 1:
userName = dbconn;
break;
case 2:
apword = dbconn;
break;
counter++;
br.close();
}catch(IOException e){
} -
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" -
How to read specific lines from a text file using external table or any other method?
Hi,
I have a text file with delimited data, I have to pick only odd number rows and load into a table...
Ex:
row1: 1,2,2,3,3,34,4,4,4,5,5,5,,,5 ( have to load only this row)
row2: 8,9,878,78,657,575,7,5,,,7,7
Hope this is enough..
I am using Oracle 11.2.0 version...
ThanksThere are various ways to do this. I would be inclined to use SQL*Loader. That way you can load it from the client or the server and you can use a SQL*Loader sequence to preserve the row order in the text file. I would load the whole row as a varray into a staging table, then use the TABLE and MOD functions to load the individual numbers from only the odd rows. Please see the demonstration below.
SCOTT@orcl12c> HOST TYPE text_file.csv
1,2,2,3,3,34,4,4,4,5,5,5,,,5
8,9,878,78,657,575,7,5,,,7,7
101,201
102,202
SCOTT@orcl12c> HOST TYPE test.ctl
LOAD DATA
INFILE text_file.csv
INTO TABLE staging
FIELDS TERMINATED BY ','
TRAILING NULLCOLS
(whole_row VARRAY TERMINATED BY '/n' (x INTEGER EXTERNAL),
rn SEQUENCE)
SCOTT@orcl12c> CREATE TABLE staging
2 (rn NUMBER,
3 whole_row SYS.OdciNumberList)
4 /
Table created.
SCOTT@orcl12c> HOST SQLLDR scott/tiger CONTROL=test.ctl LOG=test.log
SQL*Loader: Release 12.1.0.1.0 - Production on Tue Aug 27 13:48:37 2013
Copyright (c) 1982, 2013, Oracle and/or its affiliates. All rights reserved.
Path used: Conventional
Commit point reached - logical record count 4
Table STAGING:
4 Rows successfully loaded.
Check the log file:
test.log
for more information about the load.
SCOTT@orcl12c> CREATE TABLE a_table
2 (rn NUMBER,
3 data NUMBER)
4 /
Table created.
SCOTT@orcl12c> INSERT INTO a_table (rn, data)
2 SELECT s.rn,
3 t.COLUMN_VALUE data
4 FROM staging s,
5 TABLE (s.whole_row) t
6 WHERE MOD (rn, 2) != 0
7 /
17 rows created.
SCOTT@orcl12c> SELECT * FROM a_table
2 /
RN DATA
1 1
1 2
1 2
1 3
1 3
1 34
1 4
1 4
1 4
1 5
1 5
1 5
1
1
1 5
3 101
3 201
17 rows selected. -
Reading a Random Line from a Text File
Hello,
I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
Here is my code, and the text file that the program reads from is called 'wordFile'
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class WordColor extends JFrame{
public WordColor(){
super("WordColor");
setSize(1000,500);
setVisible(true);
add(new WordPanel());
public static void main(String[]r){
JFrame f = new WordColor();
class WordPanel extends JPanel implements KeyListener{
private Graphics2D pane;
private Image img;
private char[]characterList;
private CharacterPosition[]positions;
private int charcounter = 0;
private String initialWord;
private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
private FontMetrics fm;
private javax.swing.Timer timer;
public final static int START = 20;
public final static int delay = 10;
public final static int BOTTOMLINE = 375;
public final static int buffer = 15;
public final static int distance = 4;
public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
Color.magenta,Color.orange,Color.pink};
public static String[] words;
public static int descent;
public static int YAXIS = 75;
public static int SIZE = 72;
public WordPanel(){
words = readWords();
setLayout(new BorderLayout());
initialWord = getWord();
characterList = new char[initialWord.length()];
for (int i=0; i<initialWord.length();i++){
characterList[i] = initialWord.charAt(i);
setFocusable(true);
addKeyListener(this);
timer = new javax.swing.Timer(delay,new ActionListener(){
public void actionPerformed(ActionEvent evt){
YAXIS += 1;
drawWords();
if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
if (allColorsOn()) win();
public void paintComponent(Graphics g){
super.paintComponent(g);
if (img == null){
img = createImage(getWidth(),getHeight());
pane = (Graphics2D)img.getGraphics();
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
pane.setFont(new Font("Arial",Font.BOLD,SIZE));
pane.setColor(Color.black);
drawThickLine(pane,getWidth(),5);
fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
descent = fm.getDescent();
distributePositions();
drawWords();
timer.start();
g.drawImage(img,0,0,this);
private void distributePositions(){
int xaxis = START;
positions = new CharacterPosition[characterList.length];
int counter = 0;
for (char c: characterList){
CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
positions[counter] = cp;
counter++;
xaxis += fm.charWidth(c)+distance;
private void drawThickLine(Graphics2D pane, int width, int thickness){
pane.setColor(Color.black);
for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
pane.drawLine(0,j,width,j);
private void drawWords(){
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
drawThickLine(pane,getWidth(),5);
for (CharacterPosition cp: positions){
int x = cp.getX();
char print = cp.getChar();
pane.setColor(cp.getColor());
pane.drawString(""+print,x,YAXIS);
repaint();
private boolean allColorsOn(){
for (CharacterPosition cp: positions){
if (cp.getColor() == Color.black) return false;
return true;
private Color randomColor(){
int rand = (int)(Math.random()*colors.length);
return colors[rand];
private void restart(){
charcounter = 0;
for (CharacterPosition cp: positions){
cp.setColor(Color.black);
private void win(){
timer.stop();
newWord();
private void newWord(){
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
repaint();
drawThickLine(pane,getWidth(),5);
YAXIS = 75;
initialWord = getWord();
characterList = new char[initialWord.length()];
for (int i=0; i<initialWord.length();i++){
characterList[i] = initialWord.charAt(i);
distributePositions();
charcounter = 0;
drawWords();
timer.start();
private void lose(){
timer.stop();
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
pane.setColor(Color.red);
pane.drawString("Sorry, You Lose!",50,150);
repaint();
removeKeyListener(this);
final JPanel p1 = new JPanel();
JButton again = new JButton("Play Again?");
p1.add(again);
add(p1,"South");
p1.setBackground(Color.white);
validate();
again.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
remove(p1);
addKeyListener(WordPanel.this);
newWord();
private String getWord(){
int rand = (int)(Math.random()*words.length);
return words[rand];
private String[] readWords(){
ArrayList<String> arr = new ArrayList<String>();
try{
BufferedReader buff = new BufferedReader(new FileReader(wordFile));
try{
String line = null;
while (( line = buff.readLine()) != null){
line = line.toUpperCase();
arr.add(line);
finally{
buff.close();
catch(Exception e){e.printStackTrace();}
Object[] objects = arr.toArray();
String[] words = new String[objects.length];
int count = 0;
for (Object o: objects){
words[count] = (String)o;
count++;
return words;
public void keyPressed(KeyEvent evt){
char tempchar = evt.getKeyChar();
String character = ""+tempchar;
if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
positions[charcounter].setColor(randomColor());
charcounter++;
else if (evt.isShiftDown()){
evt.consume();
else{
restart();
drawWords();
public void keyTyped(KeyEvent evt){}
public void keyReleased(KeyEvent evt){}
class CharacterPosition{
private int xaxis;
private char character;
private Color color;
public CharacterPosition(char c, int x, Color col){
xaxis = x;
character = c;
color = col;
public int getX(){
return xaxis;
public char getChar(){
return character;
public Color getColor(){
return color;
public void setColor(Color c){
color = c;
}I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
class WordList extends ArrayList<String>{
long updated;
WordList readWordList(File file) throws Exception{
WordList list = new WordList();
BufferedReader in = new BufferedReader(new FileReader(file));
String line = null;
while ((line = in.readLine()) != null){
list.add(line);
in.close();
list.updated = file.lastModified();
return list;
WordList wordList;
File datFile = new File("words.dat");
File txtFile = new File("input.txt");
if (datFile.exists()){
ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
wordList = (WordList)input.readObject();
if (wordList.updated < txtFile.lastModified()){
//if the text file has been updated, re-read it
wordList = readWordList(txtFile);
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
output.writeObject(wordList);
output.close();
} else {
//serialized list does not exist--create it
wordList = readWordList(txtFile);
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
output.writeObject(wordList);
output.close();
}The text file contained one random sequence of letters per line. For example:
hwnuu
nhpgaucah
zfbylzt
hwnc
gicgwkhStats:
Text file size: 892K
Serialized file size: 1.1MB
Time to read from text file: 795ms
Time to read from serialized file: 1216ms -
Reading certain lines of a text file and boundary testing ...
Hi all,
This is only my second post so please be gentle ;P
Basically, my problem is that i want to read certain chunks of a text file into different text boxes. For example, this may be 50 lines in textbox1, then 50 in textbox2, then the rest in textbox3. i know this would involve using a splitter, but i have absolutelyno
idea how i would go about implementation this. any help would be greatly appreciated on this.
my second problem is that i also need to carry out testing on my system. one page in this is the login page. I understand that normal data would be all correct fields and erroneous data would be blank field(s). however, i dont really know what would be boundary
testing for this. The only thing i could think of is correct username but incorrect password but i dont think this is correct. again, any help would be appreciated.
thanks,
LTIDHi all,
This is only my second post so please be gentle ;P
Basically, my problem is that i want to read certain chunks of a text file into different text boxes. For example, this may be 50 lines in textbox1, then 50 in textbox2, then the rest in textbox3. i know this would involve using a splitter, but i have absolutelyno
idea how i would go about implementation this. any help would be greatly appreciated on this.
my second problem is that i also need to carry out testing on my system. one page in this is the login page. I understand that normal data would be all correct fields and erroneous data would be blank field(s). however, i dont really know what would be boundary
testing for this. The only thing i could think of is correct username but incorrect password but i dont think this is correct. again, any help would be appreciated.
thanks,
LTID
I suppose there would be a reason for needing to read some amount of lines into each textbox. But you make no mention of why that would be necessary.
There is such a thing as a delimited text file. Each line would contain a delimiter of some character between fields on each line. That file could be used for displaying information in separate controls on a Form.
But you only mention TextBox's and reading x amount of lines from a file into each TextBox as if you are perhaps providing certain information for each TextBox.
If that is what you want then provided replies will work. If you want to explain what you need to do with regard to information in a file and displaying it otherwise then please explain so that a better method could be provided.
Example using Text Field Parser.
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser(v=vs.110).aspx
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\Users\John\Desktop\DelimitedTextFile.Txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {"|"}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ListBox1.Items.Add(currentRow(0))
ListBox2.Items.Add(currentRow(1))
ListBox3.Items.Add(currentRow(2))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
End Sub
End Class
Text in text file DelimitedTextFile.Txt. Delimiter is vertical bar.
Bill|Home Depot|Garden Department
Cheryll|DirectTV|Installer
Charlie|C&K Automotive|Owner
Zorro|Television|Masked Avenger
Samantha|Mayo Clinic|Nurse Practitioner
Mona|Bahia Honda Key State Park|Park Ranger
La vida loca -
i need to delete (or replace them with white space) a few lines from a text file. I have a text file with first few lines & last few lines containing "<"or ">". I need to delete/replace with white space, the entire line. i need to do this urgently
Could some one please tell me how to do this?the file can be of size 8MB or more. i get this file
every week from a third party. So the size is not
constant. I need to remove/replace with white space,
the fist & last few lines and the rest is comma
seperated values which i need to load to database
using sqlldr. But still not sure abt how to remove
the first few lines.
i need to read this file, replace the lines as i read
them and write the replaced string back to the file &
then load the rest of lines to database.8 MByte is fairly small. Read the file a line at a time and copy to a new file only the lines you want. Should take no more than a second or so.
P.S. It will probably be a mistake if you try to edit the original file in place. -
Retrieving certain line from a text file
Hi,
I would like to know on how to read a specific line from a text file using NetBeans IDE 6.1? Below is the content of my text file and my code.I will appreciate if anyone can help. Thank in advance= D
Matrix1.text
<matrix>
rows = 2
cols = 2
1 2
2 4
</matrix>
I would like to retrieve the interger 1,2,2,4.
MyCode.java
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
class Matrix {
double [][] element;
static void getFile(String fileName) throws IOException{
int counter = 0;
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null){
line = br.readLine();
System.out.println(line);
counter ++;
System.out.println("Total line : " + counter);
br.close();
}catch(FileNotFoundException ex){
System.out.println(ex.getMessage());
}Wonders wrote:
Thank for reply=D
Yap the row and column will change but i had already parse these lines into my code. However, i am still figuring on how to get the integer number 1,2,2,4 of the text file using while loop and not include the "</matrix>" in the reading. Can this be done?If the numbers you want are at fixed byte positions in the file that are known ahead of time, you can use java.io.RandomAccessFile to skip to those positions. However, that seems unlikely.
If, as is the more likely case, those are not at fixed positions, you'll have to read everything preceding them. (Note that this is not a Java issue. This is how file I/O works.) You'll need to ignore the lines that are meaningless to you (read those lines and do nothing with them) figure out, by whatever rules you have--line numbers, preceding tokens, whatever--when you're at the lines you do care about, and then read and process those lines accordingly. -
How to read last line from a .txt file?
Hello
I have a string: e.g. "my name is John"
and i wanna verify if this string is equal with the last line from a text file
for example, if in the txt file i have:
asdasd
sdgsdfgasd
asdfgadfgadf
sdgasdgsdf
my name is john
then it's OK.
but if i have
asdgsdfg
dsfhsdfhsd
sdgasdfg
sdgsdg
my name is Jdfgsdg
this is not correct
How should i do this?
Thanks:)Read from the beginning an discard all lines (if you have a small file), or use RandomAccessFile and scan from the end till you find the beginning of the last line.
Kaj -
Reading Each String From a text File
Hello everyone...,
I've a doubt in File...cos am not aware of File.....Could anyone
plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help meThe Java� Tutorials > Essential Classes: Basic I/O
-
SQL Loader-How to insert -ve & date values from flat text file into coloumn
Question: How to insert -ve & date values from flat text file into coloumns in a table.
Explanation: In the text file, the negative values are like -10201.30 or 15317.10- and the date values are as DDMMYYYY (like 10052001 for 10th May, 2002).
How to load such values in columns of database using SQL Loader?
Please guide.Question: How to insert -ve & date values from flat text file into coloumns in a table.
Explanation: In the text file, the negative values are like -10201.30 or 15317.10- and the date values are as DDMMYYYY (like 10052001 for 10th May, 2002).
How to load such values in columns of database using SQL Loader?
Please guide. Try something like
someDate DATE 'DDMMYYYY'
someNumber1 "TO_NUMBER ('s99999999.00')"
someNumber2 "TO_NUMBER ('99999999.00s')"Good luck,
Eric Kamradt
Maybe you are looking for
-
Hi, I have a script which imports XML and formats it. As part of the formatting, there's numerous GREP searches which remove redundant spaces, returns and so on. One in particular crashes InDesign and it's driving me nuts. It's supposed to remove red
-
Post Work Exp of 8 yrs+ in HR and now Career in SAP HCM Functional Consultant
Dear Respected Members, Myself Abhinav Chandra , having a PG Degree in HR and a work experience of 8 yrs plus in HR Domain . At presently, I am associated as as Manager - Human Resources with India's 2nd largest Steel Manufacturing organization . My
-
Why does the BlackBoard HTML editor freeze and crash Firefox 3.6?
Black Board uses a HTML editor that seems to be based on JAVA. I teach by added posts to threads and can use the editor or disable the editor in either case after adding some text the window freezes and I cannot add text or delete text. If I enable t
-
Hi All Im new to flex / air and i am looking into how i can have a user login to an air app offline and storing the credentials offline as well as to track their app usage on a sqlite database. if any one has an example i appreciate it.
-
How do I prevent the itunes store coming up as a popup every time I open i tunes?
How do I prevent the i tunes store appearing as a popup each time I open i tunes? I rarely download and this is an unwanted step. Thanks