Java overwriting file - java

I have a problem now. I created a simple pet hotel application and I wanted to implement a delete function so user can remove existing booking.
//the main one.
System.out.println("---------------------------");
System.out.println("Welcome to the delete menu:");
System.out.println("---------------------------");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter owner's first name");
String firstName = scanner.nextLine();
System.out.println("Enter owner's last name");
String lastName = scanner.nextLine();
delete(firstName, lastName);
//the delete class
public static void delete(String firstName, String lastName) throws Exception
{
File inputFile = new File("BookingDetails.txt"); // Your file
File tempFile = new File("TempBooking.txt");// temp file
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null)
{
if(currentLine.contains(firstName) && currentLine.contains(lastName))
continue;
writer.write(currentLine+"\n");
}
writer.close();
}
There's a booking file already existed
Which contains this details.
Abid Akmal 03/09/2013 0129928272 Checkup File 10 250.0 Dog
Zhi Kai 12/11/2013 1029918811 Grooming Pika 1 25.0 Rabbit
Vincent Che 12/03/2013 0129817711 Grooming Fleese 2 50.0 Dog
It's a user input so when user want to delete the record, they will input for example Zhi as first name and Kai as last name, after that
a new folder TempBooking.txt appear with the other two booking details that still exist But the original BookingDetails.txt folder also is still there with the original booking record.
My problem now what's the function to overwrite the file so the temp file (TempBooking.txt) will change to BookingDetails.txt.

either you delete BookingDetails.txt and rename TempBooking.txt to BookingDetails.txt.
or
write all your content from TempBooking.txt to BookingDetails.txt

Related

How can I remove specific elements from a linkedlist in java based on user input?

I'm very new (6 weeks into java) trying to remove elements from a csv file that lists a set of students as such (id, name, grades) each on a new line.
Each student id is numbered in ascending value. I want to try and remove a student by entering the id number and I'm not sure how I can do this.
So far I've just tried to reduce the value that user inputs to match the index as students are listed by number and I did this in a while loop. However, each iteration doesn't recognize the reduction from the previous user Input, and I think I need a way that can just search the value of the id, and remove the entire line from the csv file.
Have only tried to include the pertinent code. Reading previous stack questions has shown me a bunch of answers related to nodes, which make no sense to me since I don't have whatever prerequisite knowledge is required to understand it, and I'm not sure the rest of my code is valid for those methods.
Any ideas that are relatively simple?
Student.txt (each on a new line)
1,Frank,West,98,95,87,78,77,80
2,Dianne,Greene,78,94,88,87,95,92
3,Doug,Lei,78,94,88,87,95,92
etc....
Code:
public static boolean readFile(String filename) {
File file = new File("C:\\Users\\me\\eclipse-workspace\\studentdata.txt");
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String[] words=scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}scanner.close();
}catch (FileNotFoundException e) {
System.out.println("Failed to readfile.");
private static void removeStudent() {
String answer = "Yes";
while(answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Do you wish to delete a student?");
answer = scanner.next();
if (answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Please enter the ID of the student to be removed.");
//tried various things here: taking userInput and passing through linkedlist.remove() but has never worked.
This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);

Scanner only recognizes certain lines in a text file but not others

I have a txt file of names and genders that I imported for this java program. The scanners are supposed take a user input (name and gender) and compare it line by line to find it within the text file and then print the line at which the name was found. However, only some names work and not others. I think it may be because the program only reads every other line but im not sure if thats the problem, or how to fix it.
Link to the name file: http://courses.cs.washington.edu/courses/cse142/16au/homework/names.txt
public static void fileSearch() throws FileNotFoundException {
System.out.println("What name are you looking for?");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
String gender = scan.nextLine();
File file = new File("names.txt");
Scanner fileScan = new Scanner(file);
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
String nameText = lineScan.next();
String genderText = lineScan.next();
if (name.equalsIgnoreCase(nameText) && gender.equalsIgnoreCase(genderText)) {
System.out.println(line);
}
}
}
}

Java Reading File and output to console [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So i have a tiny problem, for some reason I'm blanking and I've tried moving it inside the loop and back to the outside of the loop it doesn't work. In option two which returns method display_names it reads them from the file it writes them to the console on one line instead of two separate lines.
ex:
Enter two knew people clicking 3:
smith, rob, 123-123-1234
smith, tom, 123-123-1235
Display names by clicking 2:
smith, rob, 123-123-1234smith, tom, 123-123-1235
instead of:
smith, rob, 123-123-1234
smith, tom, 123-123-1235
Main Code:
import java.util.*;
import java.io.*;
public class ContactList
{
/**
Contact list file name
*/
private String filename;
String findMe;
/**
ContactList constructor accepts a String parameter
*/
public ContactList(String inFileName)
{
filename = inFileName;
}
/**
3) add a new record to the file. Open the file for writing in append mode(there is a FileWriter constructor with the appropriate parameters).
a) prompt the user to enter data for each field in the record. Each field is a String.
The last name is required. If the last name is the empty string(""), return to the menu.
b) when the user has completed entering data(i.e., all the fields have been prompted), re-display the user choices
c) do not overwrite existing data
*/
public void new_record()
{
/*
Prompt for data:
Last name
First name
Phone
*/
//Create a scanner object
Scanner scan = new Scanner(System.in);
//prompt for the last name
System.out.println("Last Name: ");
//input the last name
String lastName = scan.next();
//the Last_name must not be empty
if(lastName.length() > 0)
{
//get the first name and the phone
System.out.println("Enter First Name: ");
String firstName = scan.next();
System.out.println("Enter phone number(xxx-xxx-xxxx): ");
String phone = scan.next();
//create the output string
String info = String.format("%s, %s, %s", lastName, firstName, phone);
//Declare variables to hold file types
File file = new File(filename);
//try to open the file for writing - append the data
try
{
if(!file.exists()){
PrintWriter out = new PrintWriter(filename);
out.println(info);
out.flush();
out.close();
}
else if(file.exists()){
FileWriter fw = new FileWriter(filename, true);
fw.write(info);
fw.close();
}
}
catch(IOException ioe)
{
System.out.println("new_record: Exception opening the file for writing");
}
}//end of test of Last_name
}//end of new_record
/**
2) display all last names and first names in the file.
Open the file for reading, read each record and
display the field values.
a) display all the lastName, firstName paired fields in the file;
display with the format lastName, firstName
b) when all records have been displayed, display the record count - the record count is the number of records read and should equal the number of records in the file
c) after all the records and the count have been displayed, display the user choices
*/
public void display_names()
{
//delare variables to hold file types
File file = new File(filename);
//try to open the file for reading
try
{
if(file.exists()){ //if the file exists allow it to be read
BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
String line = br.readLine();
int count = 0;
System.out.println("");
while(line != null){
System.out.println(line);
line = br.readLine();
count++;
}
System.out.println("");
System.out.println("Total records read: " +count);
br.close();
}
}
catch(IOException ioe)
{
System.out.println("display_names: Exception opening the file");
}
}//end of display_names
/**
1) search an address file for a particular last name
and then display the Last name, the first name, and
the phone for each match
2) display the count of records which match the last name
*/
public void search(String LastName)
{
//Declare variables to hold file types
File file = new File(filename);
this.findMe = LastName;
//try to open the file for reading
try
{
if(file.exists()){
BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
String s="", line = null;
int count = 0;
while((line = br.readLine()) != null){
String [] parts = line.split(",");
if(parts[0].equals(findMe)){
count = 1;
s= line;
}
}
System.out.println("\n"+s+"\n");
System.out.println("Total matching records found: " +count);
br.close();
}
}
catch(IOException ioe)
{
System.out.println("search: Exception opening the file");
}
}//end of search
}//end of class
Tester Code:
import java.util.*;
public class TestContactList
{
/**
main
*/
public static void main(String args [])
{
final int ONE = 1;
final int TWO = 2;
final int THREE = 3;
final int FOUR = 4;
final int FIVE = 5;
Scanner scan = new Scanner(System.in);
/*
*/
while(true)
{
System.out.println("1) Search an address file for a particular last name ");
System.out.println("2) Display all last names and first names in the file ");
System.out.println("3) Add a new record to the file ");
System.out.println("4) End the program ");
System.out.print("Please choose 1 - 4: ");
int choice = scan.nextInt();
scan.nextLine();
/*
Create a new ContactList object with the name of the
contact list file.
*/
ContactList cl = new ContactList("MyAddressBook.txt");
/*
if 4 exit program
*/
if(choice == FOUR)
{
System.exit(0);
}
/*
if 1 call search method
*/
if(choice == ONE)
{
System.out.print("Enter name to find: ");
String findMe = scan.nextLine();
cl.search(findMe);
}
/*
if 2 call display_names method
*/
if(choice == TWO)
{
cl.display_names();
}
/*
if 3 call new_record method
*/
if(choice == THREE)
{
cl.new_record();
}
}//end of while loop
}//end of main
}
thanks in advance xD, I think this should be a simple fix
well, it seems that the data files are the ones missing here :-) but from your code
while((line = br.readLine()) != null){
s += line;
count++;
}
System.out.println("\n"+s+"\n");
it seems that you're appending your items into "s" and only in the end you're embracing it between newlines.
Instead, I think you should add the newline inside the while loop.
Of course, there are other issues like using StringBuilder or StringBuffer to concatenate strings.
Your format string (String.format) needs to have a line separator.

Java Delete a line from txt after reding the file [duplicate]

This question already has answers here:
Java - delete line from text file by overwriting while reading it
(3 answers)
Closed 8 years ago.
I have this file
1007 book1 5 3
1004 book2 4 1
1003 book3 3 0
1002 book4 2 1
and I am trying to delete the book number 1004 from the file, but before that I let the user enter the number of the book that he wants to delete.
First check if the book exists in the file or not, if the book is exists I delete it if not show "the book does not exists".
Scanner kb = new Scanner(System.in);
FileInputStream book = new FileInputStream("input.txt");
Scanner infile = new Scanner(book);
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter pw = new PrintWriter(out);
boolean found = false;
System.out.print("Enter the bookID : ");
int bID = kb.nextInt();
while(infile.hasNext()){
int id = infile.nextInt();
String title = infile.next();
int quantity = infile.nextInt();
int bQuantity = infile.nextInt();
if(bID == id){
found = true;
}
if(found == true){
pw.printf("%8d\t%-30s\t%8d\t%8d", infile.nextInt(), infile.next(), infile.nextInt(), infile.nextInt());
infile.nextLine();
System.out.println("The book has been deleted");
break;
}
}
if(found == false)
System.out.print("Not found");
pw.close();
infile.close();
I am trying to print all the file with out the book I have deleted.
You will need a book class, like this:
public class Book {
private int series;
private String name;
private int intA;
private int intB;
public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}
When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.
Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.
To read your file into this array of objects, you can do this:
public static ArrayList<Book> readbooklist() {
ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");
try {
Scanner scnr = new Scanner(file);
while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("\t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}
scnr.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
return booklist;
}
Remember to import proper dependency at the beginning of your class. Wish it helps!
I'd recommend to use a Map to store each line as value and the Id as the key only once. That way you don't have to reopen the file and read it each time you want to remove or add an entry, all you have to do is remove it and add it to the map. Once you are done, you can overwrite the old file you have by the values stored in the map or just create a new temp file to hold the data, delete the old file and then rename the temp file with old file's name
Store all the lines you would like to save in a String and close the scanner. Create a printwriter, print the string to the file and close it.
Example code:
File file = new File("yourTextFile.txt");
Scanner in = new Scanner(file);
String saveThisToFile = "";
while (in.hasNext()) {
String temp = in.nextLine();
if (condition to be true if you whant to keep this line) {
saveThisToFile += temp + "\n";
}
}
in.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(saveThisToFile);
printWriter.close();

How to read in user inputs to create objects?

I'm pretty new to Java still and I'm working on a project for class, and I'm unsure of how I write my program to take the userInput(fileName) and create a new object from that. My instructions are to write a program which reads in a file name from the user and then reads the data from that file, creates objects(type StudentInvoice) and stores them in an ArrayList.
This is where I am right now.
public class StudentInvoiceListApp {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
String fileName;
System.out.println("Enter file name: ");
fileName = userInput.nextLine();
ArrayList<StudentInvoice> invoiceList = new ArrayList<StudentInvoice>();
invoiceList.add(new StudentInvoice());
System.out.print(invoiceList + "\n");
}
You may try to write a class for serializing / deserializing objects from a stream (see this article).
Well, as Robert said, there's not enough information about the format of the data stored in the file. Suppose each line of the file contains all the information for a student. Your program will consist of reading a file by lines and create a StudentInvoice for each line. Something like this:
public static void main(String args[]) throws Exception {
Scanner userInput = new Scanner(System.in);
List<StudentInvoice> studentInvoices = new ArrayList<StudentInvoice>();
String line, filename;
do {
System.out.println("Enter data file: ");
filename = userInput.nextLine();
} while (filename == null);
BufferedReader br = new BufferedReader(new FileReader(filename));
while ( (line = br.readLine()) != null) {
studentInvoices.add(new StudentInvoice(line));
}
System.out.println("Total student invoices: " + studentInvoices.size());
}

Categories

Resources