I have write a code to print the whole text in text file but i couldn't know how to enable it to read the whole text except last line
The Code :
public class Files {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// -- This Code is to print the whole text in text file except the last line >>>
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("FileToPrint.txt"));
String s = br.readLine();
while (true) {
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(s);
s = sCurrentLine;
}
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(s);
s = sCurrentLine;
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
i want the code above can read the text except last line ,,,
thanks for help
The simplest approach is probably to print the previous line each time:
String previousLine = null;
String line;
while ((line = reader.readLine()) != null) {
if (previousLine != null) {
System.out.println(previousLine);
}
previousLine = line;
}
I'd also suggest avoiding catching exceptions if you're just going to print them out and then continue - you'd be better using a try-with-resources statement to close the reader (if you're using Java 7) and declare that your method throws IOException
.
See more on this question at Stackoverflow