Remove a Specific Line From text file - java

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();
}
}

Related

Updating a single line on a text file with a Java method

I know previous questions LIKE this one have been asked, but this question has to do with the specifics of the code that I have written. I am trying to update a single line of code on a file that will be permanently updated even when the program terminates so that the data can be brought up again. The method that I am writing currently looks like this (no compile errors found with eclipse)
public static void editLine(String fileName, String name, int element,
String content) throws IOException {
try {
// Open the file specified in the fileName parameter.
FileInputStream fStream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
fStream));
String strLine;
StringBuilder fileContent = new StringBuilder();
// Read line by line.
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(" ");
if (tokens.length > 0) {
if (tokens[0].equals(name)) {
tokens[element] = content;
String newLine = tokens[0] + " " + tokens[1] + " "
+ tokens[2];
fileContent.append(newLine);
fileContent.append("\n");
} else {
fileContent.append(strLine);
fileContent.append("\n");
}
}
/*
* File Content now has updated content to be used to override
* content of the text file
*/
FileWriter fStreamWrite = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fStreamWrite);
out.write(fileContent.toString());
out.close();
// Close InputStream.
br.close();
}
} catch (IOException e) {
System.out.println("COULD NOT UPDATE FILE!");
System.exit(0);
}
}
If you could look at the code and let me know what you would suggest, that would be wonderful, because currently I am only getting my catch message.
Okay. First off the bat, StringBuilder fileContent = new StringBuilder(); is bad practice as this file could well be larger than the user's available memory. You should not keep much of the file in memory at all. Do this by reading into a buffer, processing the buffer (adjusting it if necessary), and writing the buffer to a new file. When done, delete the old file and rename the secondary to the old one's name. Hope this helps.

Java code to remove initial lines of a file executing very slow

I have written java code to remove initial characters from a file with 200k records , the file is removing the initial characters but its reading the file line by line and removing the characters .The program is executing very slow . Any tweaks could be made to below code to execute it faster ?
The program is executing and writing the output to a file , but its very slow
import java.io.*;
import java.util.Scanner;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
File input = new File(inputfile);
Scanner scan = new Scanner(input);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while (scan.hasNext()) {
line = scan.nextLine();
line = line.substring(number_of_char_to_erased);
print.println(line);
}
scan.close();
print.close();
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
What appears to be the issue here is that you just created a buffered reader to read the file. Then, it reads the first line of the file. Then, you create a Scanner to read ALL the lines in the file, omitting certain characters. Then your BufferedReader reads the next line in the file. And the process repeats itself. So all you have to do is this:
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
print.println(line.substring(number_of_char_to_erased);
}
print.close();
This should much faster. Basically, since you've already allocated line to the read line from the file, you can simply print out that line, minus the number of chars, to the output file. The entire for loop with scanner was entirely unnecessary, and closing and opening the print stream for each line was also unnecessary.
EDIT: Removed the println statement since it would slow it down a bit.
Try this (Scanner and Println removed, output file refactored outside the loop):
import java.io.*;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
String trimmedLine = line.substring(number_of_char_to_erased);
print.println(trimmedLine);
}
// Always close files.
bufferedReader.close();
print.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}

Buffered Reader/Writer flushes files

I'm trying to create a method that replaces every line in my file with a given. Instead it just makes the file empty. Care to take a look and see what is up? Thanks.
try {
FileReader fr = new FileReader(chooser.getSelectedFile());
BufferedReader reader = new BufferedReader(fr);
FileWriter fw = new FileWriter(chooser.getSelectedFile());
BufferedWriter bw = new BufferedWriter(fw);
String line = reader.readLine();
Scanner scan = null;
int i=0;
while (line != null) {
scan = new Scanner(line);
ln = scan.toString() + add;
bw.write(ln);
bw.newLine();
i++;
System.out.println(i + " pass");
line = reader.readLine();
}
reader.close();
bw.close();
} catch (FileNotFoundException e) {
System.out.println("Can't find the file");
} catch (IOException e) {
System.out.println("Dude, it's impossibru to read.");
}
The i in this method is too see how many passes the programme goes through a while loop, in this case 0, it doesn't initiate a while loop at all.
If you want to overwrite the same file with your new lines you should do first all the reading, and then all the writing.
ArrayList<String> lines = new ArrayList<String>();
//start reader, go over each line
while (line != null) {
String newLine = //make changes to line
lines.add(newLine);
}
//close reader
//start writer
//write each line to file
You opened file in replace mode, your FileWriter will empty file before first line will be written. Use FileWriter(file,true) if you want to append.
Second problem is you are reading and writing at the same time. Try next sequence:
read whole file
replace all lines
write (replace old file)
Thus you will minimize problems count

Inserting a big text file into netbeans

try {
BufferedReader br = new BufferedReader(new FileReader("Help.txt"));
String helptext = br.readLine();
helpText.setText(helptext);
} catch (IOException e) {
System.out.println ("Error: " + e);
}
It only returns the first line of the text file and the text file is about 4 pages long.
"helptext" being a text area.I want the whole file with its spaces I made in the text area.
This will give only 1 line where in your file the first line whatever contain to get all the line you need get into the loop
StringBuffer sb = new StringBuffer();
String line = null;
while((line=br.readLine()) !=null){
sb.append(line);
}
helpText.setText(sb.toString());
You need to loop through the text file. You are only telling it to readline() one time.
EDIT: Fixed code to be exactly what user needed
EDIT 2: Added code to keep cursor at top
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("<Location of text file>"));
while((line=br.readLine()) != null){
helpText.append(line);
//Add a new line for the next entry (If you would like)
helpText.append("\n");
}
//Set Cursor back to start
helpText.setCaretPosition(WIDTH);
}
catch (IOException e) {
System.out.println (e);
}
you have to read every line in a loop.
String line = br.readLine();
String helptext = "";
while(line != null) {
helptext = helptext + line;
line = br.readLine();
}
helpText.setText(helptext);

How to read a text file into jtextarea in Java Swing

Here is my code:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null) {
textLine = reader.readLine();
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
And my .txt file contains the following:
contig00001 length=586 numreads=4
CGGGAAATTATCcGCGCCTTCACCGCCGCCGGTTCCACCGACGAACGGATACTGCGtGaa
ggCCGCGATCCCGTCggaCGGAAAaCGCCcTGGCCCGGGAaCATACCGTTCGGGCCGCCA
AGTGTTATAGCCGGACCACTTGTCAGAACATTTCCaaTCCGAAGATGTGAGTtCGGAAGg
TAAAAGCCCGACAAGTTGCGCGgTGAATTTACCTTtACcGCACGATATGCGTCCGTATTA
AaGAAAaGTTCGAAATTATCAGTAAGGCCGACCTGAAaGCTGACCGGGAGTTCAACAAAA
TCTGCATCACCcGGgTCACGGTCGAAATTGCTGTACGCGGCGCTGAACGTAAATTCACCC
TTTcTAAGGGTGTCGCcGTCGTAAACCGTAAaCAaGCCGGTAGCGCCGCCCATCGGGCCG
CCGGTACCAACCGTCGGTGCCGTGTTTCTtGCATCATTGTCCGATCGAGCGTTCTCGTCC
GCTTGTGCAAaTCCTGCAaTAGCTAACGTGAAAACGATCAGAGCTGTTGTAAATACTCTA
TAAGCGAGATTCATCACATTCCTCcGCCGAAATAAAAAGTTAATTt
contig00002 length=554 numreads=4
TGCGCCAaCCGCGCTCTtCATAAaTGGGCACTGCTCCCGATGGCCgACTCGGGCGGTTCG
CCATGAGATCTTTGCCtACCcAGgAaCtCACcACCAAGTCTGATTGCTGTGTGTTTtCTT
CAAGTCCCTATTTCTATTCtCTTtAATGGAACCCGTAGGAAACCCGTGTAGGACGCGGGA
aCCGCACTTgAAGGGGGAGGCGCGGGGTACCGGtCCGGGAACGTACGGGTACCGGCGGGG
gAGGGGAGGGGGACCgCTCCGGGAAGGCCAGGGGACGGATTGGGGAAGGgCGGGTACCGA
AGCGGGgAAaTGGGggAaCcGGCGAGAGGGTTCCTCGCTAAGTGGGGGAAATaGGGGAAA
GGTTGACCAGTGGTtCCCcGCTCTCGTAACATGCCTCAGATAGCGCCATCCGCTGTACCT
GGtcaggtcGctggcaacttcggccgagcaggtgaacccgaaaggtgagggtcagtgtga
cacaccaaccgaacaccgacgaggcaagcgtaggagccggcgtggccgcgcccggcggcg
ctgaggactcctcg
But shows the output by skipping the first two lines.
What is the reason for this?
You don't need the while loop, or the readLine method. Just call jtextArea1.read(reader, "jTextArea1")
Edit: update following your comment. If you want to skip all lines starting with >, you will need to read the file manually and then append each line to your textArea.
So something like:
String line;
while ((line = reader.readLine()) != null)
{
if (!line.startsWith(">"))
{
jTextArea.append(line + "\n");
}
}
Use:
FileReader reader = new FileReader("filename.txt");
txtarea.read(reader, "filename.txt"); //Object of JTextArea
You need only the above two lines to read from a file and put it into JTextArea...
The problem must have been solved by the time, yet there's still no answer to the question why the first two lines are skipped.
You create reader and then read the first two lines from the file, remaining lines are loaded into jTextArea1.
Your code:
/* 1 */ while((textLine=reader.readLine())!=null){
/* 2 */ textLine = reader.readLine();
/* 3 */ jTextArea1.read(reader,"jTextArea1");
}
Line 1 reads the first line from the file. Then in the body of while you read the second line from the file at line 2. Line 3 reads the rest of the file into jTextArea1.
On the next iteration of the while loop, reader.readLine() returns null since the file is completely read.
To load text in a JTextComponent use its read method as suggested by Phill and Bhushankumar.
The second parameter to read is not used by JTextArea, so it's safe to pass null. This second parameter is usually used to store to URL of the loaded file to resolve relative references, for example links in an HTMLDocument.
textLine = reader.readLine(); is called twice...
Fixed:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null){
// textLine = reader.readLine(); // Remove this line
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
Correctly is:
try {
FileReader fr = new FileReader("tablica.txt");
BufferedReader reader = new BufferedReader(fr);
do {
l.read(reader, null);
}
while ((textLine=reader.readLine()) != null)
;
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}

Categories