Remove line of Text and Rewrite File - java

Here is my code. Everything works except the last two lines. I am trying to remove a line from a .txt and rewrite the file into a tempfile and then rename the tempfile to original. The last two lines are being ignored though. Here is what the error is:
https://i.gyazo.com/66a320aeaf487837ce64fe3424074de6.png
These two lines are being ignored:
inputFile.delete();
tempFile.renameTo(inputFile);
File inputFile = new File(a.getDirectoryData() + "UserTwo.txt");
File tempFile = new File(a.getDirectoryData() + "TempUserTwo.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(a.username + ":" + a.password)) continue;
writer.write(currentLine + "\r\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);

Looks like it cannot delete a file. Can you try to use
Files.delete(inputFile.toPath())
instead?
From docs:
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Related

Won't Create Temp txt file

I would like to create a temporary txt file for my program. In the code below, "student1.txt" is a txt file that has already created but for "temporarystudent.txt" is is not. I have tried to run with Line 6 (while in Line 7 & 8 in comment) as well as Line 7 & 8 (while Line 6 in comment) but neither of them are able to create "temporarystudent.txt". When I run the program, it didn't show any error neither in VS Code Terminal nor in the Program Output. It just won't create the "temporarystudent.txt". May I know what's wrong here?
try
{
//Locate the file.
File file = new File("student1.txt");
//Create a temporary file
//File temp = File.createTempFile("temporarystudent", ".txt", file.getParentFile());
File temp = new File("temporarystudent.txt");
temp.createNewFile();
//Determine the charset.
String charset = "UTF-8";
//Open the file for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
//Open the temp file for writing.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
//Read the file line by line.
for (String line; (line = reader.readLine()) != null;) {
line = line.replace("null\n", "");
writer.println(line);
}
//Close the reader and writer (preferably in the finally block).
reader.close();
writer.close();
//Delete the file.
file.delete();
//Rename the temp file.
temp.renameTo(file);
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}

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

Deleting and renaming file

So I'm trying to delete a line of data from a file, which I have successfully done by opening a new file and writing all the information that doesn't match with the data that I would like to remove. The problem is, after I have done that, I would like to delete my original file, and then rename the new file with excludes the information I wanted to delete, to the same name as the original file. I have added in the code to do this, but for some reason it's not working.
public static void delete() throws IOException
{
File inputFile = new File("Elements.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(element)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}
As you can see near the bottom, I have these lines:
inputFile.delete();
tempFile.renameTo(inputFile);
These lines are meant to delete my original file(inputFile) and then rename my new file(tempFile) to the file name that the original file had. After running the code however, I simply get a file called "myTempFile.txt" which has succesfully deleted the line of data that I wanted, but my original file is still present and it wasn't deleted, neither was the new file renamed to the original file.
Any idea why this is happening?
Use the java.nio.file API. This is 2015.
final Path src = Paths.get("Elements.txt").toAbsolutePath();
final Path tmp = src.resolveSibling("Elements.txt.new");
try (
final BufferedReader reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
final BufferedWriter writer = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW);
) {
// yadda yadda
}
Files.move(tmp, src, StandardCopyOption.REPLACE_EXISTING);
File is unreliable. It has always been.
in such a case i would start fiddling around, reading documentation and maybe googling for a bit. But i will give you an answer, too!
inputFile.delete();
This could go wrong, for example if you have your file opened in a text editor.
Luckily delete() returns a boolean, try checking that!
Also as Niels correctly mentioned File.renameTo() is quite unrelieble if you have access to Java 7 use the files.nio alternative. In Java 7 you can use Files.move(Path source, Path target, CopyOption... options)
Docs for Java 7 Files: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
But your very code works correctly for me. I only change the path to the file and I make sure the file is not opened in editor
public class NewClass {
public static void main(String[] args) {
try {
delete();
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void delete() throws IOException {
File inputFile = new File("C:\\Users\\olyjosh\\Desktop\\Elements.txt");
File tempFile = new File("C:\\Users\\olyjosh\\Desktop\\myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if (trimmedLine.startsWith(element)) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}
}

How to edit parts of a line in a text file in java

I'm trying to delete the last four characters of all the lines in a text file. Let's say I have domain.txt and the content:
123.com
student.com
tech.net
running into hundreds of lines. How do I delete the last four characters (the extensions) to remain:
123
student
tech
etc.
I hope this helps.
UPDATED
String a ="123.com";
System.out.println(a.substring(0, a.lastIndexOf(".")));
You can do as below :
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "",
newtext = "";
while((line = reader.readLine()) != null) {
line=line.substring(0, line.lastIndexOf("."))
newtext += line + "\n";
}
reader.close();
// Now write new Content
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.close();
Do not forget to use try..catch

Remove a line in text file with java.BufferedReader

How can I remove or trim a line in a text file in Java?
This is my program but it does not work.
I want to remove a line in text file, a line contain the word of user input
try {
File inputFile = new File("temp.txt");
File tempFile = new File("temp1.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = name;
String currentLine;
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(lineToRemove))
{
// if current line not start with lineToRemove then write to file
writer.write(currentLine);
}
}
writer.close();
reader.close();
}
catch(IOException ex)
{
System.out.println("Error reading to file '" + fileName + "'");
}
You are not separating the lines with a line break character, so the resulting file will have one single long line. One possible way to fix that is just writing the line separator after each line.
Another possible problem is that you are only checking if the current line starts with the given string. If you want to check if the line contains the string you should use the contains method.
A third problem is that you are not writing the trimmed line, but the line as it is. You really don't say what you expect from the program, but if you are supposed to output trimmed lines it should look like this:
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
startsWith() is the culprit. You are checking if the line starts with "lineToRemove". As #Joni suggested use contains.

Categories