edit line in a text file - java

i've tried this code that i found in the internet
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String replace = JOptionPane.showInputDialog("Enter what to replace: ");
String toreplace = JOptionPane.showInputDialog("Enter where to replace: ");
String newtext = oldtext.replaceAll(replace, toreplace);
FileWriter writer = new FileWriter("file.txt");
writer.append(newtext);writer.close();
but mine won't output like this code will do. the output of this code is like this:
unedit:
jojo moyes
kim possible
dexter laboratory
edited: when i enter "mary" to edit "kim"
jojo moyes
mary possible
dexter laboratoty
but mine will be like this
jojo moyes
kim possible
dexter laboratoy
mary possible
mine tho had register before editing. and in the register there is also time that it will store something in the text file. and there goes the edit function if the user wants to edit something in the information that he entered (you get the picture)
EDITED: here's my code
public void Register_Edit_Info() throws IOException{
FileWriter writeFile=new FileWriter("voters.txt", true);
BufferedWriter outFile=new BufferedWriter(writeFile);
File readFile=new File("voters.txt");
BufferedReader read=new BufferedReader(new FileReader(readFile));
String choice2;
String [] secondMenu = {"Register", "Edit", "Delete", "Back"};
do{
choice2=(String)JOptionPane.showInputDialog(null, "Please choose:", "Election 2765", 1, null, secondMenu, secondMenu[0]);
switch(choice2){
case "Register":
String [] menuGender={"Male", "Female"};
String [] menuStatus={"Single", "Married", "Widow(er)", "Legally separated"};
do{
age=Integer.parseInt(JOptionPane.showInputDialog("Age: "));
while(age<18){
JOptionPane.showMessageDialog(null, "Voter should be 18 or above");
age=Integer.parseInt(JOptionPane.showInputDialog("Age: "));
}
name=JOptionPane.showInputDialog("Full Name: ");
gender=(String)JOptionPane.showInputDialog(null, "Gender:", "Election 2765", 1, null, menuGender, menuGender[0]);
if(gender=="Male"){
gender="Male";
}
else{
gender="Female";
}
dBirth=JOptionPane.showInputDialog("Date of Birth: ");
pBirth=JOptionPane.showInputDialog("Place of Birth: ");
address=JOptionPane.showInputDialog("Address\n(Province, City/Municipality, Barangay, House No./Street: ");
status=(String)JOptionPane.showInputDialog(null, "Civil Status:", "Election 2765", 1, null, menuStatus, menuStatus[0]);
if(status=="Single"){
status="Single";
}
else if(status=="Married"){
spouse=JOptionPane.showInputDialog("Spouse Name: ");
status="Married(Spouse: "+spouse+")";
}
else if(status=="Widow(er)"){
status="Widow(er)";
}
else{
status="Legally Separated";
}
citizenship=JOptionPane.showInputDialog("Citizenship:");
job=JOptionPane.showInputDialog("Profession/Occupation: ");
tin=JOptionPane.showInputDialog("Tin Number: ");
father=JOptionPane.showInputDialog("Father's Full Name: ");
mother=JOptionPane.showInputDialog("Mother's Full Name: ");
votersNumber++;
vNumber=Integer.toString(votersNumber);
outFile.append(vNumber+"/"+name+"/"+age+"/"+gender+"/"+dBirth+"/"+pBirth+"/"+address+"/"+status+"/"+citizenship+"/"+job+"/"+father+"/"+mother);
outFile.newLine();
selectYN=JOptionPane.showInputDialog("You are now registered. Do you want to register more?\n[1]Yes [2]No");
}while(!"2".equals(selectYN));
break;
case "Edit":
vNumForEdit=JOptionPane.showInputDialog("Enter voters number: ");
String line=null, oldtext="";
while((line=read.readLine())!=null){
oldtext+=line+"\n";
String [] info=line.split("/");
if(info[0].matches(vNumForEdit)){
String [] forEditMenu={"Name", "Age", "Gender", "Date of Birth", "Place of Birth", "Address", "Civil Status", "Citizenship", "Profession/Occupation", "Father's Name", "Mother's Name"};
forEdit=(String)JOptionPane.showInputDialog(null, line+"\n\nPlease select what you want to edit", "National Election 2765", 1, null, forEditMenu, forEditMenu[0]);
switch(forEdit){
case "Name":
oldName=JOptionPane.showInputDialog("Enter old name: ");
newName=JOptionPane.showInputDialog("Enter new name: ");
String newText = oldtext.replaceAll(oldName, newName);
outFile.append(newText);
break;
}
}
}
case "Delete":
break;
}
}while(choice2!="Back");
read.close();
outFile.close();
}

This Answer is for the first portion of your question.(before edit).
public static void main(String[] args) throws FileNotFoundException,IOException {
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
System.out.println(oldtext);
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String replace = JOptionPane.showInputDialog("Enter what to replace: ");
String toreplace = JOptionPane.showInputDialog("Enter where to replace: ");
String newtext = oldtext.replaceAll(replace, toreplace);
System.out.println(newtext);
java.io.FileWriter writer = new java.io.FileWriter("file1.txt");
writer.write(newtext);
writer.close();
}
When first prompt open I write "kim" and where to replace , I write "marry" and the output like this. I think your code is fine except not to use append() for FileWriter. you should use write() method for FileWriter.
EDIT:
Use different file name (I don't know about if reading and writing operation occur for same file.) for FileWriter and for initialization you can use
FileWriter writeFile=new FileWriter("voters1.txt");
And let me know if the problems is solved.

Related

Read two text files and write specific lines from those two text files into a third file

I am creating a hospital management system in which I have 2 classes namely AddDoctor and AddPatient which takes the input from user about their details and stores them into their respective files. I now want to create an Appointment class in which I can assign a patient with a certain ID to a doctor with a certain ID which are read from the files. This would be very easy if Java supported multiple inheritance, but since it doesn't, I'm stuck on how I could do this task.
Following is my AddDoctor class
class AddDoctor{
int did;
int dage;
long dphno;
String dname;
String dgender;
String dqualification;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
void input() throws IOException{
System.out.print("Enter Doctor's Name:");
dname = br.readLine();
Random rand = new Random();
did = rand.nextInt((9999 - 100) + 1) + 10;
System.out.print("Enter Doctor's Phone Number:");
dphno = Long.parseLong(br.readLine());
System.out.print("Enter Doctor's Age:");
dage = Integer.parseInt(br.readLine());
System.out.print("Enter Doctor's Gender:");
dgender = br.readLine();
System.out.print("Enter Doctor's Qualification:");
dqualification = br.readLine();
}
void delete() throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("DoctorDetails.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the ID of the Doctor you wish to delete: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
void search() throws IOException{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID of the Doctor To Search:");
String did=scan.next();
String line="";
try{
FileInputStream fin = new FileInputStream("DoctorDetails.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine()){
line=sc.nextLine();
if(line.startsWith(did))
System.out.println(line+" ");
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
void display(){
try{
BufferedReader br=new BufferedReader(new FileReader("DoctorDetails.txt"));
String s="";
while((s=br.readLine())!=null){
String data[]=new String[6];
data=s.split(" ");
for(int i=0;i<6;i++){
System.out.print(data[i]+"\t");
}
System.out.println();
}
br.close();
}
catch(Exception e){
}
}
};
//Class WriteD to Write Doctor Details in a text file where the details are fetched from the Class AddDoctor
class WriteD extends AddDoctor {
void write() {
try(FileWriter fw = new FileWriter("DoctorDetails.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(did + " " + dname + " " + dphno + " " + dage + " " + dgender + " " + dqualification);
}catch(IOException e){
e.printStackTrace();
}
}
};
Following is my AddPatient Class
class AddPatient extends People{
String pillness;
String pregisterdate;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
void input() throws IOException{
System.out.print("Enter Patient's Name:");
name = br.readLine();
Random rand1 = new Random();
id = rand1.nextInt((9999 - 100) + 1) + 10;
System.out.print("Enter Patient's Phone Number:");
phno = Long.parseLong(br.readLine());
System.out.print("Enter Patient's Age:");
age = Integer.parseInt(br.readLine());
System.out.print("Enter Patient's Gender:");
gender = br.readLine();
System.out.print("Enter Patient's Illness:");
pillness = br.readLine();
System.out.print("Enter Patient's Registration Date:");
pregisterdate = br.readLine();
}
void delete() throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("PatientDetails.txt");
File tempFile = new File("myTemp2.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the ID of the Patient you wish to delete: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
void search() throws IOException{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID of the Patient To Search:");
String did=scan.next();
String line="";
try{
FileInputStream fin = new FileInputStream("PatientDetails.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine()){
line=sc.nextLine();
if(line.startsWith(did))
System.out.println(line);
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
void display(){
try{
BufferedReader br=new BufferedReader(new FileReader("PatientDetails.txt"));
String s="";
while((s=br.readLine())!=null){
String data[]=new String[7];
data=s.split(" ");
for(int i=0;i<7;i++){
System.out.print(data[i]+"\t");
}
System.out.println();
}
br.close();
}
catch(Exception e){
}
}
};
class WriteP extends AddPatient {
void write() {
try(FileWriter fw = new FileWriter("PatientDetails.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(String.format("%-1s %-1s %-1s %-1s %-1s %-1s %-1s",id,name,phno,age,gender,pillness,pregisterdate));
}catch(IOException e){
e.printStackTrace();
}
}
};
Simple solution is using composition create object of doc and patient in appointment class and get doc and patient id from user or create one using objects and write it in third file.
In case of Id you need to search info from file.
In case of new information, as you will be creating object of doctor and patient. first right them in their files and then store data in third file as you want.
If it answer your question let me know.
Create an appointment class and use a search method that accepts the ids to look for (which would look similar to the search methods you already have) then utilize code similar to your write to write to the new file.

Java delimiter on a text file

I am trying to read a txt file with this format (heading not included):
firstname lastname username password
John Doe $1234567 $123
Eden Hask $1234576 $12345
The latest login (Eden) would always work but not the one prior(John).
For some reason, the delimiter would include all details until the next $.
How should I get my delimiter to stop after the password.
The user name is_1234567 and the password is_123
Eden Hask!
The user name is_1234576 and the password is_12345!
Here is the entire code.
public void login() throws FileNotFoundException{
File file = new File("file.txt");
Scanner read = new Scanner(file);
found = false;
read.useDelimiter("(\s*\\$)");
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String user = read.next();
String pass = read.next();
System.out.println("The user name is_" + user + " and the password is_" + pass + "!\n");
if(user.trim().equals(username) && pass.trim().equals(passwordField)){
boolean found = true;
break;
}
}
if(found){
return true;
}
else {
return false;
}
read.close();
}catch(Exception e){
throw e;
}
};
I would do it completely different:
boolean found;
public void login() throws FileNotFoundException {
File file = new File("file.txt");
Scanner read = new Scanner(file);
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String password = keyboard.nextLine();
// Skip the first line
read.nextLine();
while (read.hasNextLine()) {
String line = read.nextLine();
//split current line with spaces into an array
String[] lineArray = line.split("\\s+");
String user = lineArray[1];
String pass = lineArray[4];
System.out.println("The user name is " + user + " and the password is " + pass + "!\n");
if (user.equals(username) && pass.equals(password)) {
found = true;
break;
}
}
read.close();
keyboard.close();
} catch (Exception e) {
e.printStackTrace();
}
}
From what you have described it looks like you also want to break your string when a line ends. To do this add a carriage return as one of delimiting cases in the following manner-
read.useDelimiter("\n|(\s*\\$)")
this should prevent all the previous 'password' strings from including details from the next line
In addition to the line break inclusion in the delimiter, you may want to read the name of the user to keep the userid/password reads in sync:
read.useDelimiter("(\\s*\\$)|(\\R)");
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String name = read.next();
String user = read.next();
String pass = read.next();

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

Filtering specific team from text file and displaying results

I want my program to allow a user to enter a team name and based on that name it will distribute the pertinent team information to the console for viewing. So far, the program allows the user to input a text file that contains unformatted team data. It then formats that data, stores it and prints the information to the console. It is at this point in my program where I want the user to be able to start her/his filtering based on a team name. I am not necessarily looking for an exact answer but some helpful tips or suggestions would be appreciated.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
System.out.println();
Scanner fileReader = null;
//A list to add results to, so they can be printed out after the parsing has been completed.
ArrayList<LineResult> results = new ArrayList<>();
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
while(fileReader.hasNext()) {
String line = fileReader.nextLine();// Read a line of data from text file
// this if statement helps to skip empty lines
if ("".equals(line)) {
continue;
}
String [] splitArray = line.split(":");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
//This section checks if each line has any corrupted data
//and then display message to the user.
if("".equals(splitArray[0]))
{
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}else if ("".equals(splitArray[1])) {
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}
try {
// Extract each item into an appropriate variable
LineResult result = new LineResult();
result.homeTeam = splitArray[0];
result.awayTeam = splitArray[1];
result.homeScore = Integer.parseInt(splitArray[2]);
result.awayScore = Integer.parseInt(splitArray[3]);
results.add(result);
} catch(NumberFormatException e) {
System.out.println(line + " > Home team score may not be a valid integer number ");
System.out.println(" or it may be missing");
System.out.println();
}
}else {
System.out.println(line + " > The field delimiter may be missing or ");
System.out.println(" wrong field delimiter is used");
System.out.println();
}
}
System.out.println();
System.out.println();
//Print out results
System.out.println("Home team Score Away team Score");
System.out.println("========= ===== ========= =====");
//Loop through each result printing out the required values.
//TODO: REQ4, filter results based on user requested team
try (BufferedReader br = new BufferedReader(new File(filename));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
for (LineResult result : results) {
System.out.println(
String.format("%-15s %1s %-15s %1s",
result.homeTeam,
result.homeScore,
result.awayTeam,
result.awayScore));
}
// end of try block
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
System.out.println();
}
}
//Data object for holding a line result
static class LineResult {
String homeTeam, awayTeam;
int homeScore, awayScore;}
}

How to display specific data from a file

My program is supposed to ask the user for firstname, lastname, and phone number till the users stops. Then when to display it asks for the first name and does a search in the text file to find all info with the same first name and display lastname and phones of the matches.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class WritePhoneList
{
public static void main(String[] args)throws IOException
{
BufferedWriter output = new BufferedWriter(new FileWriter(new File(
"PhoneFile.txt"), true));
String name, lname, age;
int pos,choice;
try
{
do
{
Scanner input = new Scanner(System.in);
System.out.print("Enter First name, last name, and phone number ");
name = input.nextLine();
output.write(name);
output.newLine();
System.out.print("Would you like to add another? yes(1)/no(2)");
choice = input.nextInt();
}while(choice == 1);
output.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
Here is the display code, when i search for a name, it finds a match but displays the last name and phone number of the same name 3 times, I want it to display all of the possible matches with the first name.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class DisplaySelectedNumbers
{
public static void main(String[] args)throws IOException
{
String name;
String strLine;
try
{
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
strLine= br.readLine();
String[] line = strLine.split(" ");
String part1 = line[0];
String part2 = line[1];
String part3 = line[2];
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
if(name.equals(part1))
{
// Print the content on the console
System.out.print("\n" + part2 + " " + part3);
}
}
}catch (Exception e)
{//Catch exception if any
System.out.println("Error: " + e.getMessage());
}
}
}
you need to split your line and set your parts inside the while loop:
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
String[] line;
String part1, part2, part3;
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
line = strLine.split(" ");
part1 = line[0];
part2 = line[1];
part3 = line[2];
if(name.equals(part1))
{
System.out.print("\n" + part2 + " " + part3);
}
}

Categories

Resources