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
Similar Messages
-
How to read partcicular line from a txt file
in a text file let there be 50 lines
while reading the line if the line is having "name" as a string in that line then i have to store the next two consecutive lines in a string as array....
Similar way and so on......
How can we do this....You need a BufferedReader:
http://java.sun.com/j2se/1.4.2/docs/api/java/io/BufferedReader.html
for example:try {
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
String line;
while ( (line=br.readLine()) != null ) {
if (line.indexOf("name") != -1) {
// Store the next two lines.
// You will need to call br.readLine() again.
} catch (IOException x) {
x.printStackTrace();
} -
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 -
How to read Chinese word from a TXT file
File.OpenText() read a TXT File with Chinese word in ;but it not show right.
exam:The TXT File include :中国
this.Txt1.Text=ofd.File.OpenText().ReadToEnd();
but it show :��ʹ�ݼƻ��
How to solve itWhat encoding does the text file use? Unlike .NET, Silverlight only supports UTF-8 and UTF-16. File.OpenText() uses UTF-8 by default.
If the text file is in some other encoding, you can create your own encoding class (that derives from System.Text.Encoding) that can be used to read the text file.
class MyEncoding : System.Text.Encoding {
this.Txt1.Text = (new StreamReader(ofd.File.OpenRead(), new MyEncoding())).ReadToEnd();
Regards,
Justin Van Patten
Program Manager
Common Language Runtime -
How to read multiple lines from an external file to the Oracle data base
Hi Guys,
I have an external file which contains multiple lines and I want to read it to the data base .I have done it for the file if it contains one line.
Please guide me how to retrieve all the lines into the data base.And also tell me how Oracle will come to know the end of the line in the file
Thanks,
PrafullaHi,
try this
CREATE TABLE ab
a VARCHAR2(1 BYTE),
b VARCHAR2(2 BYTE),
c VARCHAR2(10 BYTE),
d VARCHAR2(11 BYTE)
ORGANIZATION EXTERNAL
( TYPE ORACLE_LOADER
DEFAULT DIRECTORY dir_name
ACCESS PARAMETERS
( records delimited by newline
fields (
a POSITION(*) CHAR(1),
b POSITION(*) CHAR(2 ),
c POSITION(*) CHAR(10 ),
d POSITION(*) CHAR(11 )
LOCATION (dir_name:'filename.txt')
REJECT LIMIT UNLIMITED
NOPARALLEL
NOMONITORING;
Regards,
Simma.... -
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. -
How to read the last line in a txt file?
Dear all,
I want to read the last line in a txt file. There are thousands of lines in this file. What I want is to move the file pointer directly to the last line of the file. But I did not know how do to it. Can anybody help me out?
Thank you very much!If the file is coded as ASCII or one of the encodings that maps a single byte to a char then the following class will assist you
import java.io.*;
import java.util.*;
public class GetLinesFromEndOfFile
static public class BackwardsFileInputStream extends InputStream
public BackwardsFileInputStream(File file) throws IOException
assert (file != null) && file.exists() && file.isFile() && file.canRead();
raf = new RandomAccessFile(file, "r");
currentPositionInFile = raf.length();
currentPositionInBuffer = 0;
public int read() throws IOException
if (currentPositionInFile <= 0)
return -1;
if (--currentPositionInBuffer < 0)
currentPositionInBuffer = buffer.length;
long startOfBlock = currentPositionInFile - buffer.length;
if (startOfBlock < 0)
currentPositionInBuffer = buffer.length + (int)startOfBlock;
startOfBlock = 0;
raf.seek(startOfBlock);
raf.readFully(buffer, 0, currentPositionInBuffer);
return read();
currentPositionInFile--;
return buffer[currentPositionInBuffer];
public void close() throws IOException
raf.close();
private final byte[] buffer = new byte[4096];
private final RandomAccessFile raf;
private long currentPositionInFile;
private int currentPositionInBuffer;
public static List<String> head(File file, int numberOfLinesToRead) throws IOException
return head(file, "ISO-8859-1" , numberOfLinesToRead);
public static List<String> head(File file, String encoding, int numberOfLinesToRead) throws IOException
assert (file != null) && file.exists() && file.isFile() && file.canRead();
assert numberOfLinesToRead > 0;
assert encoding != null;
LinkedList<String> lines = new LinkedList<String>();
BufferedReader reader= new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
for (String line = null; (numberOfLinesToRead-- > 0) && (line = reader.readLine()) != null;)
lines.addLast(line);
reader.close();
return lines;
public static List<String> tail(File file, int numberOfLinesToRead) throws IOException
return tail(file, "ISO-8859-1" , numberOfLinesToRead);
public static List<String> tail(File file, String encoding, int numberOfLinesToRead) throws IOException
assert (file != null) && file.exists() && file.isFile() && file.canRead();
assert numberOfLinesToRead > 0;
assert (encoding != null) && encoding.matches("(?i)(iso-8859|ascii|us-ascii).*");
LinkedList<String> lines = new LinkedList<String>();
BufferedReader reader= new BufferedReader(new InputStreamReader(new BackwardsFileInputStream(file), encoding));
for (String line = null; (numberOfLinesToRead-- > 0) && (line = reader.readLine()) != null;)
// Reverse the order of the characters in the string
char[] chars = line.toCharArray();
for (int j = 0, k = chars.length - 1; j < k ; j++, k--)
char temp = chars[j];
chars[j] = chars[k];
chars[k]= temp;
lines.addFirst(new String(chars));
reader.close();
return lines;
public static void main(String[] args)
try
File file = new File("/usr/share/dict/words");
int n = 10;
System.out.println("Head of " + file);
int index = 0;
for (String line : head(file, n))
System.out.println(++index + "\t[" + line + "]");
System.out.println("Tail of " + file);
int index = 0;
for (String line : tail(file, "us-ascii", n))
System.out.println(++index + "\t[" + line + "]");
catch (Exception e)
e.printStackTrace();
}Note, the EOL characters are treated as line separators so you will probably need to read the last two lines (think about it for a bit). -
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..
-
I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
Attachments:
try2.txt 2 KB
read_array.vi 21 KBThe problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
Here are some of your choices to fix your problem.
1. Change the source file to a tab delimited file. Your VI will then run as is.
2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does. -
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. -
Populate a table reading the data from a TXT file
how can I populate a table reading the data from a TXT file?
thanksHey Kevin!
Using FORMS.TEXT_IO to bulk load data from a file strikes me as re-inventing the wheel. It is just about justifiable in a self-service environment, but I regard the EXTERNAL TABLE is a better solution for that situation as well.
The same applies to UTL_FILE. I think the ability to read text with UTL_FILE is primarily intended for read file-based configuration or file manipulation/processing rather than data loading.
Re-writing a text file into SQL statements is too much like hard work (even with an editor that supports macro definition and regular expressions) for no real benefit. You lose all the bulk load peformance you would get from SQL*Loader. But for QAD I'd probably let you off with it.
You missed out one obvious alternative: using Java to turn the contents of an XML file into a CLOB and inserting it into a table which is read by a PL/SQL procedure that parses the XML records and insert the retrieved data into a table.
Stay lucky, APC -
What is the 'quickest' way to read char data from a txt file
Hello,
What is the 'quickest' way to read character data from a txt file stored on the phone to be displayed into the screen?
RegardsTo be even a bit more constructive...
Since J2me does not have a BufferedInputStream, it will help to implement it yourself. It's much faster since you read large blocks at ones in stread of seperate chars.
something line this lets you read lines very fast:
while ( bytesread < filesize ) {
length = configfile.read( buff, 0, buff.length );
// append buffer to temp String
if ( length < buff.length ) {
byte[] buf = new byte[length];
System.arraycopy( buff, 0, buf, 0, length );
tmp.append( new String( buf ) );
} else {
tmp.append( new String( buff ) );
// look in tmp string for \r\n
idx1 = tmp.toString().indexOf( "\r\n" );
while ( idx1 >= 0 ) {
//if found, split into line and rest of tmp
line = tmp.toString().substring( 0, idx1 );
/// ... do with it whatever you want ... ////
tmp = new StringBuffer( tmp.toString().substring( idx1 + 2 ) );
idx1 = tmp.toString().indexOf( "\r\n" );
bytesread += length;
} -
How to select LAST line from a SAP table?
Hi developers,
I need to select the last line from a SAP table, NOT from an internal table.
Something like
SELECT SINGLE LAST FROM pa00169..
any help is more than welcome.Javier,
Based on this statement from you:
"i created a Z table, its a config table that stores some bussines rules, and an id counter, so in order to update that counter i need the last line of the ztable."
I have one additional solution which is the "text box" approach IF the 'id counter' mentioned above is a numeric data type.
If so, use an SQL function to get the highest value of ID_COUNTER.
Then simply add one to it to produce a new, unique, higher-order primary key.
See below:
data: l_id_counter like ztable-id_counter.
data: new_id_counter like ztable-id_counter.
select max( ID_COUNTER ) from ztable into l_id_counter.
new_id_counter = l_i_counter + 1.
Now new_id_counter will be the unique, primary key IF this is the only field in ZTABLE's primary key.
This will also GUARANTEE that your new record is built correctly. -
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"
Maybe you are looking for
-
recently i got a new DVD/CD drive for my laptop, from doing this I can no longer sync my iPod. I've been able to upload songs into my library but when i plug my iPod in iTunes doesn't reconize it. When i first open iTunes it's asking me that i need t
-
How do I get rid of this annoying feature in Safari known as cover flow which appears as a balck void in bookmarks? the bookmarks manager is nowhere to be found and now I'm going to Google instead of Safari.
-
HT1386 My Itunes wont play it just jumps through all of the music titles
When I try to play music from Itunes it just jumps quickly through the titles and wont play music.
-
Vendor code creation with HR data
Hi, Is there any way to get vendor code created automatically, while creating the HR data (Personnel No.)? Because the same details we are using except Recon.Account. Regards Prakash.
-
Actual difference between exterprise oracle 9i/10edition & standard edition
hi, i want to know the actual difference between exterprise oracle 9i/10edition & standard edition. plz reply me. thanks, regards.