My apologies for the title wording, it was hard to explain in words. What I am trying to do I this:
I have a .txt file that has
cheese cracker salt
bread butter ham
I want the user to be able to enter 'cheese' then type in pepper which will in turn update the file to become
cheese cracker pepper
bread butter ham
I am unsure how to go about editing the third word after I have the user input the first word.
CodePudding user response:
Your algorithm could look like this:
- read in the file
- split it up by spaces (you will get an array)
- put the result into a modifiable list (you can't easily insert into an array)
- search for the index of a word
- insert another entry by index (you can calculate the correct index from the result of step 4)
- overwrite the file with the contents of the list, separated by additional spaces.
CodePudding user response:
Here is a solution utilizing File
module along with BufferedReader
/BufferedWriter
packages
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.nio.file.*;
Driver program
public class Main{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");
String path = sc.nextLine();
Path p = Paths.get(path);
List <String> lines = Files.readAllLines(p);
System.out.println("Enter new word:");
String newWord = sc.nextLine();
System.out.println("Which word would you like " newWord " to replace?");
String oldWord = sc.nextLine();
for(int i = 0; i < lines.size(); i ){
String line = lines.get(i);
line = line.replace(oldWord, word); // if current word is old word, replace with new one
lines.set(i, line); // update list
}
readFile(path); // read here will output original list
writeListToFile(lines, path); // overwrite sample.txt file
readFile(path); // read here will output updated text file from path
sc.close();
}
helper functions
public static void readFile(String fileName){
try{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null){
System.out.println(line);
line = br.readLine();
}
br.close();
}catch(IOException e){
System.out.println("Error reading file");
}
}
public static void writeListToFile(List<String> list, String path){
try{
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < list.size(); i ){
bw.write(list.get(i));
bw.newLine();
}
bw.close();
}catch(IOException e){
System.out.println("Error writing to file");
}
}
}