how to read last line in a text file using java [duplicate] - java

This question already has answers here:
Quickly read the last line of a text file?
(10 answers)
Closed 9 years ago.
I am making a log and I want to read the last line of the log.txt file, but I'm having trouble getting the BufferedReader to stop once the last line is read.
Here's my code:
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Here's a good solution. In your code, you could just create an auxiliary variable called lastLine and constantly reinitialize it to the current line like so:
String lastLine = "";
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
lastLine = sCurrentLine;
}

This snippet should work for you:
BufferedReader input = new BufferedReader(new FileReader(fileName));
String last, line;
while ((line = input.readLine()) != null) {
last = line;
}
//do something with last!

Related

How to read value in CSV file

Need help from you regarding a Scenario, i.e., I have to take a value from DB like "42258258.2300" and convert this into "42,258,258.00" value.
And again need to check whether this value present in downloaded CSV file.
I used below code for read from CSV file but am not getting the output. Kindly help me on this.
String strFile = "outputfile.csv";
FileInputStream fstream = new FileInputStream(strFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String ss = "$42,699,561.00";
if(strLine.contains(ss)){
System.out.println ("Success"); }
}
in.close();
What do you get if you print strLine? Are you really getting the string?
This code works for me
public void getFileInformation(){
String strFile = "/Users/myUser/Documents/outputfile.csv";
BufferedReader br = null;
String strLine = "";
String ss = "$42,699,561.00";
try {
br = new BufferedReader(new FileReader(strFile));
while ((strLine= br.readLine()) != null) {
if(strLine.contains(ss)){
System.out.println ("Success");
}else{
System.out.println (strLine);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But the content "$42,699,561.00"; should really exist in the file

Java IOException - Stream Closed

I get "IOException: Stream Closed" when I run this program. The text contains many lines of data. Program should read each line, do necessary function and write the output to a new file. I am confused as to which writer should be closed first and where.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
try {
// change this value
FileInputStream fis = new FileInputStream("C:\\Users\\Rao\\Desktop\\test.txt");
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
processLine(sCurrentLine); //error
}
} finally {
if (br != null)
br.close();
}
}
public static void processLine(String line) throws IOException {
String prename = line.substring(22);
int siz= prename.indexOf(":");
String name = prename.substring(0, siz);
URL oracle = new URL("http://ip-api.com/json/"+name);
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) // error
// System.out.println(inputLine);
in.close();
String baby = (line + "\t" + inputLine);
try {
FileWriter writer = new FileWriter("C:\\Users\\Rao\\Desktop\\output.txt", true);
writer.write(baby);
writer.write("\r\n"); // write new line
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The exception is as follows:
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at URLReader.processLine(URLReader.java:31)
at URLReader.main(URLReader.java:13)
You close the input stream in your loop:
while ((inputLine = in.readLine()) != null) // error
// System.out.println(inputLine);
in.close();
You should close the stream outside of the loop:
while ((inputLine = in.readLine()) != null) // error
{
//dosomething
// System.out.println(inputLine);
}
in.close();
You should put a function call in the while loop, like:
a System.out.println("Hi, I'm a row!"); or
uncomment System.out.println(inputLine); or
put a semicolon at the end of the while statement
in order to let it to execute properly.
The code as it is written executes (comments omitted):
...
while ((inputLine = in.readLine()) != null)
in.close();
...
so the first cycle of the loop executes correctly and runs in.close(). Then the second cycle the call inputLine = in.readLine() fails because the stream is closed and then the exception is thrown.

NullPointerException reading line from file [duplicate]

This question already has answers here:
Java if/else behaving strangely
(4 answers)
Closed 7 years ago.
I have this code:
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("hello.txt"));
String line;
while ((line = br.readLine().trim()) != null) {
if (line.startsWith("Hello")) {
line = br.readLine().trim();
} else {
... code ...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But once the file reaches the end, I get this error:
Exception in thread "main" java.lang.NullPointerException
On the line:
while ((line = br.readLine().trim()) != null) {
Why? How to fix it?
Try the following; ine which you are trying to read is null hence calling trim throws NPE;
while (br.readLine() != null)
{
line = br.readLine().trim()
}
while ((line = br.readLine().trim()) != null)
remove the trim()
and added it within the while loop.
line = line.trim();
When you try to read using readLine()
line = br.readLine().trim())
if br.readLine() return null, then calling trim() cause NPE.
while ((line = br.readLine()) != null) {
line.trim();
if (line.startsWith("Hello")) {
if ((line = br.readLine()) != null) {
line.trim();
}
} else {
}
}

How to read CSV from 2nd Line in java?

I have a comma delimited CSV file ans I have the code to read it from 2nd line. But it gives me the following error.
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
This is my Code.
public static List<String> readCSV(String path){
BufferedReader br = null;
String[] cd = null;
String line ="";
String split=",";
List<String> list = new ArrayList<String>();
try {
br=new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
boolean firstLine = true;
while (line != null && line.startsWith("child's Last Name")) {
if (firstLine) {
firstLine = false;
continue;
} else {
list.add(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
How can I fix it with this code..
Thanks in Advance!
In your second while loop where are you assigning line again
while (line != null && line.startsWith("child's Last Name"))
Once this condition is satisfied, you are not reassigning it.
Your code should be different something like,
boolean firstLine = true;
while ((line = br.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
continue;
}
else if(line != null && line.startsWith("child's Last Name"))
{
list.add(line);
}
}
try
br=new BufferedReader(new FileReader(path));
boolean firstLine = true;
while ((line = br.readLine()) != null) {
if (line.startsWith("child's Last Name")) {
if (firstLine) {
firstLine = false;
continue;
}
list.add(line);
}
}
There is no need for two while loops
Your problem has nothing to do with the 2nd line; You're simply trying to put the whole file in list and eventually, there's just too much to fit in memory. You have two choices:
Do not keep it all in memory! Process the line, do what you must, and don't store it, so it eventually gets garbage collected
If you really really must keep it all in memory, try increasing the amount of heap space available by starting java with a -Xmx parameter (run java -X for details)
UPDATE: oh oops, yes, as others said, you're also stuck in and endless loop. Consider this answer only once you've fixed that!
Usually, you get an out of memory error when you... well... run out of memory to run the application. Have you debugged into it? You could be stuck in an endless loop...
while (line != null && line.startsWith("child's Last Name")) {
Should this be an if statement?
EDIT:
while ((line = br.readLine()) != null) {
This really should be:
while(br.hasNext()) {
More info: Java - Read CSV with Scanner()
try this..
br=new BufferedReader(new FileReader(path));
br.readLine();
while ((line = br.readLine()) != null) {
if (line.startsWith("child's Last Name")) {
list.add(line);
}
}

how to read line by line in android?

i am using this code.
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((br.readLine()) != null) {
temp1 = br.readLine();
temp2 = br.readLine();
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
but this is showing exception and is not updating temp1 and temp2.
The exception you see - that I would strongly recommend a) to catch as a specific type, e.g. IOException, and b) to log or show with a message or a stack trace, and c) at least to check for in LogCat, from the DDMS perspective if you are programming with Eclipse - is probably due to Android not finding the config.txt file you are trying to open. Usually, for the simplest cases such as yours, files that are private to an application are opened using openFileInput - see the documentation for details.
Apart from the exception, your reading loop is defective: you need to initialize an empty string before entering, and fill it in the while condition.
String line = "";
while ((line = br.readLine()) != null) {
// do something with the line you just read, e.g.
temp1 = line;
temp2 = line;
}
However, you don't need a loop if you just want to save the first two lines in different variables.
String line = "";
if ((line = br.readLine()) != null)
temp1 = line;
if ((line = br.readLine()) != null)
temp2 = line;
As others have already pointed out, calling readLine consumes a line, so if your config.txt file contains only one line your code consumes it on the while condition, then temp1 and temp2 get null assigned because there's no more text to read.
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
temp1 = line;
temp2 = line;
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
br.readLine() in while already consumes a line.
Try this
LineNumberReader reader = new LineNumberReader(new FileReader("config.txt")));
String line;
while ((line = reader.readLine()) != null) {
//doProcessLine
}
if you want to save the first two lines you have to do:
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
if((line = br.readLine()) != null)
temp1 = line;
if((line = br.readLine()) != null)
temp2 = line;
}
catch(Exception e)
{
e.printStackTrace();
}

Categories

Resources