Read last line from a file - java

So I am trying to read a file in Java. It works fine, unless the last line is empty, in which case it gets ignored; but I need to read this empty line too.
Here is my code:
try
{
BufferedReader in = new BufferedReader(new FileReader("filename.txt"));
String Line;
while((Line = in.readLine()) != null)
{
System.out.println("L| " + Line);
}
}
catch(Exception e){e.printStackTrace();}
}

first use scanner class...as they are hum easier to use....and then store each line in a list and then get the last line..here is the code:
public void readLast()throws IOException{
FileReader file=new FileReader("E:\\Testing.txt"); //address of the file
List<String> Lines=new ArrayList<>(); //to store all lines
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){ //checking for the presence of next Line
Lines.add(sc.nextLine()); //reading and storing all lines
}
sc.close(); //close the scanner
System.out.print(Lines.get(Lines.size()-1)); //displaying last one..
}

Related

Java Reading in text file and outputting it to new file with removed duplicates

I have a text file with an integer on each line, ordered from least to greatest, and I want to put them in a new text file with any duplicate numbers removed.
I've managed to read in the text file and print the numbers on the screen, but I'm unsure on how to actually write them in a new file, with duplicates removed?
public static void main(String[] args)
{
try
{
FileReader fr = new FileReader("sample.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
}
catch (IOException e) {
out.println("File not found");
}
}
When reading the file, you could add the numbers to a Set, which is a data structure that doesn't allow duplicate values (just Google for "java collections" for more details)
Then you iterate through this Set, writing the numbers to a FileOutputStream (google for "java io" for more details)
Instead of printing each of the numbers, add them to an Array. After you've added all the integers, you can cycle through the array to remove duplicates (sample code for this can be found fairly easily).
Once you have an array, use BufferedWriter to write to an output file. Example code for how to do this can be found here: https://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Alternatively, use a Set, and BufferedWriter should still work in the same way.
assuming the input file is already ordered:
public class Question42475459 {
public static void main(final String[] args) throws IOException {
final String inFile = "sample.txt";
try (final Scanner scanner = new Scanner(new BufferedInputStream(new FileInputStream("")), "UTF-8");
BufferedWriter writer = new BufferedWriter(new FileWriter(inFile + ".out", false))) {
String lastLine = null;
while (scanner.hasNext()) {
final String line = scanner.next();
if (!line.equals(lastLine)) {
writer.write(line);
writer.newLine();
lastLine = line;
}
}
}
}
}

Remove a Specific Line From text file

I trying to remove a specific line from a file. But I have a problem in deleting a particular line from the text file. Let's said, my text file I want to remove Blueberry in the file following:
Old List Text file:
Chocolate
Strawberry
Blueberry
Mango
New List Text file:
Chocolate
Strawberry
Mango
I tried to run my Java program, when I input for delete and it didn't remove the line from the text file.
Output:
Please delete:
d
Blueberry
Remove:Blueberry
When I open my text file, it keep on looping with the word "Blueberry" only.
Text file:
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
My question is how to delete the specific line from the text file?
Here is my Java code:
String input="Please delete: ";
System.out.println(input);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
String inFile="list.txt";
String line = "";
while(!line.equals("x"))
{
switch(line)
{
case "d":
line = reader.readLine();
System.out.println("Remove: " + line);
String lineToRemove="";
FileWriter removeLine=new FileWriter(inFile);
BufferedWriter change=new BufferedWriter(removeLine);
PrintWriter replace=new PrintWriter(change);
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
replace.close();
change.close();
break;
}
System.out.println(input);
line = reader.readLine();
}
}
catch(Exception e){
System.out.println("Error!");
}
Let's take a quick look at your code...
line = reader.readLine();
//...
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
Basically, you read the first line of the file and then repeatedly compare it with the lineToRemove, forever. This loop is never going to exit
This is a proof of concept, you will need to modify it to your needs.
Basically, what you need to ensure you're doing, is you're reading each line of the input file until there are no more lines
// All the important information
String inputFileName = "...";
String outputFileName = "...";
String lineToRemove = "...";
// The traps any possible read/write exceptions which might occur
try {
File inputFile = new File(inputFileName);
File outputFile = new File(outputFileName);
// Open the reader/writer, this ensure that's encapsulated
// in a try-with-resource block, automatically closing
// the resources regardless of how the block exists
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
// Read each line from the reader and compare it with
// with the line to remove and write if required
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.equals(lineToRemove)) {
writer.write(line);
writer.newLine();
}
}
}
// This is some magic, because of the compounding try blocks
// this section will only be called if the above try block
// exited without throwing an exception, so we're now safe
// to update the input file
// If you want two files at the end of his process, don't do
// this, this assumes you want to update and replace the
// original file
// Delete the original file, you might consider renaming it
// to some backup file
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename " + outputFileName + " to " + inputFileName);
}
} else {
throw new IOException("Could not delete original input file " + inputFileName);
}
} catch (IOException ex) {
// Handle any exceptions
ex.printStackTrace();
}
Have a look at Basic I/O and The try-with-resources Statement for some more details
Reading input from console, reading file and writing to a file needs to be distinguished and done separately. you can not read and write file at the same time. you are not even reading your file. you are just comparing your console input indefinitely in your while loop.In fact, you are not even setting your lineTobeRemoved to the input line. Here is one way of doing it.
Algorithm:
Read the console input (your line to delete) then start reading the file and looking for line to delete by comparing it with your input line. if the lines do not match match then store the read line in a variable otherwise throw this line since you want to delete it.
Once finished reading, start writing the stored lines on the file. Now you will have updated file with one line removed.
public static void main(String args[]) {
String input = "Please delete: ";
System.out.println(input);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String line = reader.readLine();
reader.close();
String inFile = "list.txt";
System.out.println("Remove: " + line);
String lineToRemove = line;
StringBuffer newContent = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(inFile));
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
newContent.append(line);
newContent.append("\n"); // new line
}
}
br.close();
FileWriter removeLine = new FileWriter(inFile);
BufferedWriter change = new BufferedWriter(removeLine);
PrintWriter replace = new PrintWriter(change);
replace.write(newContent.toString());
replace.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

Unable to compare last word in the file

I have been trying to compare the input file with the database file. The code compares the files and outputs the words from the input file(test.txt) that are present in the database file(db.txt). But however I am not getting the last word from the input file in the output.
test.txt contains:
There is a book on the table
db.txt contains:
book
the
table
Thus here I am not getting table in the output.
public static void main(String[] args) {
try {
File file = new File("G:\\Project\\test.txt");
File file2 = new File("G:\\Project\\db.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
StringTokenizer st = new StringTokenizer(stringBuffer.toString()," ");
while (st.hasMoreTokens())
{
String word=st.nextToken();
BufferedReader br = new BufferedReader(new FileReader(file2));
String lin;
while((lin=br.readLine())!=null){
{ if(word.equalsIgnoreCase(lin))
System.out.println(word);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Output received:
book
the
What is it that I am doing wrong here?
You are appending newline character to stringbuffer and that is causing this issue.
Remove below line from your code and try, it will work.
stringBuffer.append("\n");

How to remove old data from text file using user input in Java

I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.
public static void searchFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner keyboard = new Scanner(System.in);
// String lines = keyboard.nextLine();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile + "is found already");
System.out.println("would you like to rewrite new data?");
String go = keyboard.nextLine();
if (go.equals("yes")) {
// Here i want to remove old data in the file if the user types yes then rewrite new data to the file.
}
}
}
}
I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file.
I have appended code bellow, hope this helps.
File f = new File("D:\\test.txt");
File f1 = new File("D:\\test.out");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while((line = br.readLine()) != null){
if(line.contains(s)){
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if(go.equals("yes")){
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);

How to keep formatting while reading files

I'm trying to read a .java file into a JTextArea and no matter what method I use to read in the file the formatting is never preserved. The actual code is ok but the comments always get messed up. Here are my attempts.
//Scanner:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(file);
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
//output is a JTextArea
output.append(line + newline);
}
}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}
//Scanner reading the full text at once:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(file);
fileScanner.useDelimiter("\\Z");
String fullText = fileScanner.next();
//print to text area
output.append(fullText + newline);
}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}
//BufferedReader:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
//Scanner fileScanner = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line = "";
while((line = reader.readLine()) != null)
{
output.append(line + newline);
}
}
Is there anyway to keep the formatting the same??
PS - Also posted at http://www.coderanch.com/t/539685/java/java/keep-formatting-while-reading-files#2448353
Hunter
Use the JTextArea.read(...) method.
It may be due the var newline being hardcoded as '\n' or something like that. Try defining newline as follows:
String newline=System.getProperty("line.separator");
This solution is more "general", but I would use camickr solution if working with a JTextArea

Categories