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.
Related
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());
}
For the record, I know that reading the text file to a string does not ALWAYS result in an empty string, but in my situation, I can't get it to do anything else.
I'm currently trying to write a program that reads text from a .txt file, manipulates it based on certain arguments, and then saves the text back into the document. No matter how many different ways I've tried, I can't seem to actually get text from .txt file. The string just returns as an empty string.
For example, I pass in the arguments "-c 3 file1.txt" and parse the arguments for the file (the file is always passed in last). I get the file with:
File inputFile = new File(args[args.length - 1]);
When I debug the code, it seems to recognize the file as file1.txt and if I pass in the name of a different file, which doesn't exist, and error is thrown. So it is correctly recognizing this file. From here I have attempted every type of file text parsing I can find online, from old Java version techniques up to Java 8 techniques. None have worked. A few I've tried are:
String fileText = "";
try {
Scanner input = new Scanner(inputFile);
while (input.hasNextLine()) {
fileText = input.nextLine();
System.out.println(fileText);
}
input.close();
} catch (FileNotFoundException e) {
usage();
}
or
String fileText = null;
try {
fileText = new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
I've tried others too. Buffered readers, scanners, etc. I've tried recompiling the project, I've tried 3rd party libraries. Still just getting an empty string. I'm thinking it must be some sort of configuration issue, but I am stumped.
For anyone wondering, the file seems to be in the correct place, when I reference the wrong location an exception is thrown. And the file DOES in fact have text in it. I've quadruple checked.
Even though your first code snippet might read the file, it does in fact not store the contents of the file in your fileText variable but only the file's last line.
With
fileText = input.nextLine();
you set fileText to the contents of the current line thereby overwriting the previous value of fileText. You need to store all the lines from your file. E.g. try
static String read( String path ) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
for (String line = br.readLine(); line != null; line = br.readLine()) {
sb.append(line).append('\n');
}
}
return sb.toString();
}
My suggestion would be to create a method for reading the file into a string which throws an exception with a descriptive message whenever an unexpected state is found. Here is a possible implementation of this idea:
public static String readFile(Path path) {
String fileText;
try {
if(Files.size(path) == 0) {
throw new RuntimeException("File has zero bytes");
}
fileText = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
if(fileText.trim().isEmpty()) {
throw new RuntimeException("File contains only whitespace");
}
return fileText;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
This method checks 3 anomalies:
File not found
File empty
File contains only spaces
I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)
Im still new in java and can't fully understand how BufferedReader and FileWriter really work so some of this were uploaded.This code must delete a line that the user wants to but instead of a line..it deletes the whole file content
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter student number:");
title = titlerem.next ();
System.out.print("Are you sure you want to delete it [Y/N]?");
String tString = titlerem.next();
char temp2 = tString.charAt(0);
switch(temp2)
{
case('Y'):
{
// construct temporary file
File inputFile = new File("phonebook.txt");
File tempFile = new File(inputFile + " ");
BufferedReader br = new BufferedReader (new FileReader("phonebook.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
while((line = br.readLine()) !=null) {
if(line.trim().startsWith(title)){
continue;
}
else{
Pwr.println(line);
Pwr.flush();
}
}
// delete book file before renaming temp
inputFile.delete();
// close readers and writers
Pwr.close();
br.close();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Deletion succesful");
}
else
{
System.out.println("Update failed");
}
}
case('N'):
{
System.out.print("Deletion did not proceed");
break;
}
}
Can anybody help me.
I believe your code is good except that you don't have break in your switch case statements. So even if the file is properly created and renamed, you will always get the message from the second case statements which may be misleading as it says: Deletion did not proceed
First check on the file system , if contents are edited as it should be even without not having a break statement. If yes, then simply correct your switch cases by adding a break statement.
I have a method like this:
public int getIncrement() {
String extractFolder = "/mnt/sdcard/MyFolder";
boolean newFolder = new File(extractFolder).mkdir();
int counter = 0;
try {
File root = new File(extractFolder);
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.txt");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
Scanner scanner = new Scanner(new FileInputStream(gpxfile.getAbsolutePath()), "UTF-8");
Log.i("PATH: ", extractFolder + "/gpxfile.txt");
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", Integer.toString(counter));
}
counter++;
out.write(Integer.toString(counter));
out.close();
}
} catch (IOException e) {
Log.e("GEN_PCN: ", "Could not write file " + e.getMessage());
}
return counter;
}
What I am trying to accomplish is returning the content of this file, and increment the integer by 1. But it seems that I can't get in the while loop, because LogCat doesn't print out anything. Yes, am sure that the path is correct.
I guess the constructor of FileWriter gpxwriter has already blanked out the file by the time the Scanner is created, so the file is empty and hasNextLine returns false. Why do you open a file for writing when you want to read it?
From what I can tell the file doesn't exist. Try adding gpxfile.createNewFile()
To get a little more in depth, creating a File instance, does not create a file on the file system.
So, this line -> File gpxfile = new File(path, filename);
is not sufficient to create the file on the sd card. You must follow it with
gpxfile.createNewFile() which quoting the docs says:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
OK I MARK YOUR FILE NAME
Just add a BACKSLASH in extractFolder at END
v
v
v
String extractFolder = "/mnt/sdcard/MyFolder/";
^ // <--- HERE
^
^
Because File gpxfile = new File(root, "gpxfile.txt"); doesn't have BackSlash / as Log have
Just try Once Following:
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
// // counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", inc);
System.out.println("Next Line ::"+inc); // Also check this
}