Java remove complete line from file [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I am trying to remove a complete line from a text file, and have managed to remove the line if there is only one single unbroken line of text without spaces. If i have a space delimiter between strings it fails to remove anything.
Code as follows:
import java.io.*;
import java.util.Scanner;
public class removebooks {
// construct temporary file
public static void main(String[]args)throws IOException {
String title;
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter Title to remove from file");
title = titlerem.next ();
// construct temporary file
File inputFile = new File("books.txt");
File tempFile = new File(inputFile + "temp.txt");
BufferedReader br = new BufferedReader (new FileReader("books.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
//read from original, write to temporary and trim space, while title not found
while((line = br.readLine()) !=null) {
if(line.trim().equals(title)){
continue; }
else{
Pwr.println(line);
Pwr.flush();
}
}
// close readers and writers
br.close();
Pwr.close();
titlerem.close();
// delete book file before renaming temp
inputFile.delete();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Update succesful");
}else{
System.out.println("Update failed");
}
}
}
the text file is called books.txt and contents simply should look like:
bookone author1 subject1
booktwo author2 subject2
bookthree author3 subject3
bookfour author4 subject4
thank you any help would be appreciated

Why don't you use
if(line.trim().startsWith(title))
instead of
if(line.trim().equals(title))
because equals() is only true if both strings are equal, and startsWith() is true if line.trim() starts with title ;)

As you are reading the file line by line. You can make use of following
if(line.contains(title)){
// do something
}
In this case you will not be limited by title only.
String API

br.readLine() sets the value of variable line to "bookone author1 subject1".
Scanner.next() delimits by whitespace. You need to consolidate all your calls to Scanner.next() to a single String before checking against the lines in the file, if that is your intent.
In your case, if you typed "bookone author1 subject1", value of variable title would be "bookone" after your call to Scanner.next().

Related

Read line by line from text file and save each line to different cell in array

I'm trying to split each line from a text file into cells in an Array. Can I do it with split function and not count the lines in order to create an array?
I am using Scanner for reading files from Scanner. The file contains in each line the following format: number_number
I want to save number_number as a string into a cell in Array.
However, I don't know how many lines in my text file could be, in order to set an array size. I dont want to useLinkedList`, please use the assumption that will not have many lines.
Is it possible to read from file and save each line into cell in array?
There is no problem to change the method from Scanner to another one.
The problem in my code currently that it saves only the first line in my file.
public String[] readFromFileToStringArray(String s) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(s));
} catch (IOException e) {
e.printStackTrace();
}
String[] fileText = null;
if (scanner != null)
while (scanner.hasNext())
fileText = scanner.nextLine().split("\n");
return fileText;
}
When using scanner.nextLine() you read the text until the \n character, so the split you did is pointless since the line string won't have this character.
You can read all the file and then split it:
public String[] readFromFileToStringArray(String s) {
String text = new String(Files.readAllBytes(Paths.get(s)),
StandardCharsets.UTF_8);
return text.split("\n");
}
But really as the other answered said, it would probably be better to simply use List
Should you change the way to add string to the array?
fileText.add(scanner.nextLine());
OR:
List<String> list = new ArrayList<String>(Arrays.asList(fileText));
list.addAll(Arrays.asList(scanner.nextLine().splite("\n")));
String[] fileText = list.toArray();
List<String> lines = Files.readAllLines(pathToFile);
java Files is the easiest way for this.

File manipulation (changing lines in a File) in java

I'm trying to read in a file and change some lines.
The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."
Here is the code I've written so far
import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {
public static void main(String[] args) throws Exception{
System.out.println("Enter a String and the file name.");
if(args.length != 2) {
System.out.println("Input invalid. Example: John filename");
System.exit(1);
}
//check if file exists, if it doesn't exit program
File file = new File(args[1]);
if(!file.exists()) {
System.out.println("The file " + args[1] + " does not exist");
System.exit(2);
}
/*okay so, I need to remove all instances of the string from the file.
* replacing with "" would technically remove the string
*/
try (//read in the file
Scanner in = new Scanner(file);) {
while(in.hasNext()) {
String newLine = in.nextLine();
newLine = newLine.replaceAll(args[0], "");
}
}
}
}
I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.
Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?
Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?
Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.
Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.
There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.
List<String> lines = new ArrayList<>();
try {
Scanner in = new Scanner(file);
while(in.hasNext()) {
String newLine = in.nextLine();
lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
}
in.close();
// save all new lines to input file
FileWriter fileWriter = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(fileWriter);
lines.forEach(printWriter::print);
printWriter.close();
} catch (IOException ioEx) {
System.err.println("Error: " + ioEx.getMessage());
}

Cannot get PrintWriter to replace text in file

I am trying to complete a simple program that uses the command line to replace a specified String in a file. Command line entry would be java ReplaceText textToReplace filename
The code completes, but the file does not replace the specified string. I have Googled similar situations but I cannot figure out why my code is not working.
import java.io.*;
import java.util.*;
public class ReplaceText{
public static void main(String[] args)throws IOException{
if(args.length != 2){
System.out.println("Incorrect format. Use java ClassName textToReplace filename");
System.exit(1);
}
File source = new File(args[1]);
if(!source.exists()){
System.out.println("Source file " + args[1] + " does not exist.");
System.exit(2);
}
File temp = new File("temp.txt");
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(input.hasNext()){
String s1 = input.nextLine();
String s2 = s1.replace(args[0], "a");
output.println(s2);
}
temp.renameTo(source);
source.delete();
}
}
}
Edit: edited the code so I am not reading and writing to the file at the same time, but it still does not work.
First of all you have a problem with your logic. You are renaming your temporary file then immediately deleting it. Delete the old one first, then rename the temporary file.
Another problem is that you are attempting to do perform the delete and rename within your try block:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
...
temp.renameTo(source);
source.delete();
}
Your streams are not automatically closed until the try block ends. You will not be able to rename or delete while the stream is open. Both delete and renameTo return a boolean to indicate whether they were successful so it may be prudent to check those values.
Correct code may look something like:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(...)
{
...
}
}
// Try block finished, resources now auto-closed
if (!source.delete())
{
throw new RuntimeException("Couldn't delete file!");
}
if (!temp.renameTo(source))
{
throw new RuntimeException("Couldn't rename file!");
}
You can't replace strings a file in general. You need to read the input line by line, replace each line as necessary, and write each line to a new file. Then delete the old file and rename the new one.

White Spaces Java Text File

Is is possible to remove the white spaces of a String in a text file in Java? I have tried my approach but doesn't working.
public static void main(String[] args) throws IOException {
File f = new File("ejer2.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String linea = br.readLine();
linea.replaceAll("\\s", "");
while (linea != null) {
System.out.println(linea);
linea = br.readLine();
}
br.close();
}
The only way I can get the white spaces out of the String is when I print the line out in the While loop by using the replaceAll method in the String class, but im trying to take them out of the Stringin the File, and I'm not sure if this is possible.
Try with this:
linea = linea.replaceAll("\\s+","")
EDIT: It is because you didn't save the value of your new string in your variable linea. You have to asign it.
If you want to actually replace the spaces in the file, you need to write to the file instead of just reading from it.
You'll need to add a linea.replaceAll line inside your while loop.
You'll need to store all these lines as well - I suggest using a Stringbuilder and adding everything you read to the builder (after you run replaceAll).
You'll also need to write the final text to the text file. I suggest using a PrintStream.
eg: PrintStream out = new PrintStream(new FileOutputStream("finalFile.txt"));
then out.print(yourStringBuilder.toString())

reading text file and assigning strings from file to variables

I have a few problems with my code. I want to be able to read input from a text file and take the strings from each line or between spaces and assign them to variables that I will pass to an object.
My first problem is that my program misreads one of my lines and omits the first letter from a variable, and the second problem is I don't know how to make my program read two strings on the same line and assign them to different variables.
System.out.println("Input the file name of the text file you want to open:(remember .txt)");
keyboard.nextLine();
String filename=keyboard.nextLine();
FileReader freader=new FileReader(filename);
BufferedReader inputFile=new BufferedReader(freader);
courseName=inputFile.readLine();
while (inputFile.read()!= -1) {
fName=inputFile.readLine();
lName=inputFile.readLine();
officeNumber=inputFile.readLine();
}
System.out.println(fName);
Instructor inst=new Instructor(fName,lName,officeNumber);
System.out.println(inst);
inputFile.close();
}
I am not very good at using filereader and have tried to use the scanner keyboard method, but it lead me to even more errors :(
Output:
Input from a file (F) or keyboard (K):
F
Input the file name of the text file you want to open: (remember .txt)
test.txt
un bun
un bun won won's office number is null
text file:
professor messor
bun bun
won won
You have to read one line with readLine() then you say that you want to split with whitespace.
So you have to do something like this
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
String[] arrayLine= line.split("\\s+"); // here you are splitting with whitespace
courseName = arrayLine[0]
lName=arrayLine[1];
officeNumber=arrayLine[2];
list.add(new Course(courseName,lName,officeNumber));
// you sure want do something with this create an object for example
}
// in some part br.close();
Here you have an example How to read a File
When you call read() in the condition of the while loop, the "cursor" of the BufferedReader advances one character. You don't want to do this to check if the stream can be read, you want to use the ready() method.
This is another solution using StringTokenizer
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
StringTokenizer sToken = new StringTokenizer(input, " ");
list.add(new Course(sToken.nextToken(),sToken.nextToken(),sToken.nextToken()));
}

Categories