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());
}
Related
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.
I was trying to remove the first line in text file using java code referencing from this link but still the scanner does not contain any text, so it write nothing in the text file, please help, what is then problem...?
here is a peace of code,
File path=new File("C:/Users/kassim Ismail/workspace/Coding/textdoc.txt");
Scanner scan=new Scanner(path);
FileWriter newread=new FileWriter("C:\\Users\\kassim Ismail\\workspace\\Coding\\textdoc.txt");
BufferedWriter newreader=new BufferedWriter(newread);
while(scan.hasNextLine()){
String nextline=scan.nextLine();
if(nextline.equals("\n")){
newreader.newLine();
}else{
newreader.write(nextline);
}
}
scan.close();
newreader.close();
newread.close();
}
Right now I don't see any mistake in your code (reader/writer should work). One thing I am unsure about is wether the blank space in your Filepath is problematic or not (Some programs can't work with blank spaces in file paths I am not sure about Java though).
Maybe you could add some System.out.println("") statements for debugging purposes. For Example (testing if the input file exists):
System.out.println("Inputfile exists: "+path.exists())
printing the read line:
System.out.println("Read line: "+nextline)
private boolean removeTopLine(File file){
try{
boolean status = false;
Scanner s = new Scanner(file);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String content = "";
int counter = 0;
while (s.hasNextLine()){
if (counter > 0){
content += s.nextLine();
}
counter++;
}
writer.write(content);
writer.close();
status = true;
}
catch (Exception e){
e.printStackTrace();
}
return status;
}
This is a functional code snippet that would delete the first line of a file however there could be debate on efficiency.
I want to read a text file , change some text then output to a text file. I'd open this file in notepad
New to Java - This has been rehashed and posted in different way throughout the forum. They always seem to say your missing the /n in the string - I thought I did this in the below code.
The part that is confusing to me is it displays in my terminal correctly when I use the showfile method.
I assume its the way I'm writing the file. I'd like to continue to use my method instead of the String variable
Original file contains text
Bob
Red
Door
I use this to read the text file and input it in a string.
public void readFile(String fileName)
{
fileText = "";
try
{
Scanner file = new Scanner(new File(fileName));
while (file.hasNextLine())
{
String line = file.nextLine();
fileText += line +"\n";
}
file.close();
}
catch (Exception e)
{
System.out.println(e);
}
I use a method to swap all "R"s to "B"s.
I use showFile method and it displays in my terminal correctly
This shows correctly
Bob
Bed
Door
public String showFile()
{
return fileText;
}
But then I try output the string to a file using.
try {
File file = new File("test1.txt");
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(startupModified.showFile());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
It keeps my spacing but I loose my line breaks
Displays:
Bob
Bed
Door
This is the constructor class for startupModified
public StartUpFile(String fileName)
{
readFile(fileName);
}
functions correctly now
changed fileText += line +"\n";
to fileText += line +"\r\n";
I assumed it was the writer because it displayed correctly in the terminal.
Thank you
I am working on a program that involves me having to search a specific line in a .txt file and convert the string inside of it into something else.
For example, the string is actually made of numbers which I suppose I can convert into ints. The main thing is that for example, on line 2, there are 5 digits for zip code stored. I need to convert that into certain outputs, depending on the numbers. In other words, I need variables from digits 0-9 and depending on each digit, output a specific output.
Right now here is the code I have to prompt the user for information that is stored in the file, and can read and print all of the information that was just typed, but I'm unsure how to go about the rest.
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
public class ObjectTest2 {
public static void main(String [] args) throws FileNotFoundException, IOException {
// The name of the file to open.
String fileName = "information.txt";
Scanner myScanner = new Scanner(System.in);
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// append a newline character.
//This shit here prompts the user for information and stores it in seperate lines to be
//called on by the later section.
System.out.print("What is your name? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your 5 digit zip code?");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your +4 digit zip? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your address? ");
bufferedWriter.write(myScanner.nextLine());
// Always close files.
bufferedWriter.close();
//reads the information file and prints what is typed
BufferedReader reader = new BufferedReader(new FileReader("information.txt")); {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
You are left with no choice but to iterate over each line of the file and search for the String. If you want to get a line of string from the file based on line number, consider creating a method. If the operation is required to be performed several times on the same file and if the contents of the file do not change, use a map to cache the file contents based on the line number.
I'm reading .txt file into my program and am adding lines of the .txt into a String arrayList. How do I add lines DELINEATED BY AN ENTER KEY (in .txt) into separate elements of the arrayList? Right now if I had the following written in text:
this is a test
test
test test
It would output:
this is a testtesttest test
What I want it to do is read things on a per line basis, and put it into different elements of the stringArrayList. So I want "this is a test" to be an element, and "test", and then finally "test test".
My code is really ugly, but right now all I want to do is get it to work for my purpose. My first purpose is getting to read a .txt by line. My second purpose is going to be parsing an element for a particular substring (a URL), connecting that URL to the internet, and then comparing a part of that page source of the webpage (parsing for a particular keyword) to the line ABOVE the substring I desire. But that's a question for another time :^)
import java.io.*;
import java.util.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "test.txt";
List<String> listA = new ArrayList<String>();
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
listA.add(line);
//*** THIS IS WHERE THE MAGIC HAPPENS ***\\ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open da file ofheee hah. '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
System.out.println();
System.out.println("array FOr loop thingy incoming:");
System.out.println();
for (int i = 0; i < listA.size(); i++) {
System.out.print((listA.get(i)).toString());
}
}
}
You just have to use println instead of print:
System.out.println((listA.get(i)).toString());
Alternatively, you can add the line break character \n
Your code seems to be working so far. If you just want to see what elements are in listA, just print it out:
System.out.println(listA);
Output:
[this is a test, , test, , test test, ]
Note that the extra lines in your input file are also being stored in listA. I'm not sure if that's the behavior you want.