简体   繁体   中英

possible already open file error; halted

So, when I run this, I get no exceptions, but the execution halts. I entered a few lines of code to see where the hault is coming from. On initial execution, it creates a file in the path given in the Customer class. Once I do one of the actions, it doesn't let me go past the first debugging line. Ideas?

Heres the application: package javaapplication18.pkg3;

import java.util.ArrayList;
 import java.util.Scanner;
public class JavaApplication183 {

/**
 * @param args the command line arguments
 */
static boolean keepGoing = true;
public static void main(String[] args) {
    System.out.println("Welcome to the Customer Maintenance application");
    //keepGoing = true;
    Scanner sc = new Scanner(System.in);
    while (keepGoing){
        displayMenu();
        String userChoice = getRequiredString("Enter a command: ", sc);
        System.out.println("DEBUG LINE 1");


        CustomerTextFile textFile = new CustomerTextFile();
        System.out.println("DEBUG LINE 2");
        performAction(userChoice, textFile);
        System.out.println("DEBUG LINE 3");

    }
    // TODO code application logic here
}

public static void displayMenu() {
    System.out.println();
    System.out.println("COMMAND MENU");
    System.out.println("list    - List all customers");
    System.out.println("add     - Add a customer");
    System.out.println("del     - Delete a customer");
    System.out.println("help    - Show this menu");
    System.out.println("exit    - Exit this application");
    System.out.println();
}



public static void performAction(String choice, CustomerTextFile textFile){
    Scanner sc = new Scanner(System.in);
    switch (choice.toLowerCase()) {
        case "list":    
            //action
            ArrayList<Customer> currentList = textFile.getCustomers();
            for (Customer c : currentList) {
                System.out.print(c.getEmail() + "\t");
                System.out.print(c.getFirstName() + "\t");
                System.out.println(c.getLastName());
                }
            break;
        case "add":
            String email = getRequiredString("Enter customer email address:", sc);
            String firstName = getRequiredString("Enter first name:", sc);
            String lastName = getRequiredString("Enter last name:", sc);
            Customer c = new Customer(email, firstName, lastName);
            textFile.addCustomer(c);
            System.out.println(firstName + lastName + " was added to the database.");
            break;
        case "del":

            String deleteUserByEmail = getRequiredString("Enter customer email to delete:", sc);
            Customer delCustomer = textFile.getCustomer(deleteUserByEmail);
            textFile.deleteCustomer(delCustomer);
            break;
        case "help":
            //displayMenu();
            break;
        case "exit":
           keepGoing = false;//exit();
           break;
        default:
            System.out.println("You entereed something not in the list. Please try again.");
            System.out.println();
    }
}


public static boolean exit(){
    System.out.println("Exit");
    return false;
    }

public static String getRequiredString(String prompt, Scanner sc) {
String s = "";
boolean isValid = false;
while (isValid == false) {
    System.out.print(prompt);
    s = sc.nextLine();
            if (s.equals("")) 
                System.out.println("Error! This entry is required. Try again.");
            else 
                isValid = true;
            }
    return s;
}

}

Here is the CustomerTextFile class:

package javaapplication18.pkg3;

import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;

public class CustomerTextFile implements CustomerDAO{
    private ArrayList<Customer> customers = null;
    private Path customersPath = null;
    private File customersFile = null;

public CustomerTextFile(){

    customersPath = Paths.get("customers.txt");
    customersFile = customersPath.toFile();
    customers = this.getCustomers();

}
@Override
public Customer getCustomer(String emailAddress) {
    for (Customer c : customers) {
        if (c.getEmail().equals(emailAddress))
                return c;
    }
    return null;

    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public ArrayList<Customer> getCustomers() {
    if (customers != null)
        return customers;

    customers = new ArrayList<>();

    if (!Files.exists(customersPath)) {
        try {
            Files.createFile(customersPath);
        }
        catch (IOException e) {
            return null;
        }
    }

    if (Files.exists(customersPath)) {
        try (BufferedReader in = new BufferedReader(new FileReader(customersFile))){
            String line = in.readLine();
            while(line != null) {
                String[] columns = line.split("\t");
                String email = columns[0];
                String firstName = columns[1];
                String lastName = columns[2];

                Customer c = new Customer(email, firstName, lastName);
                customers.add(c);

            }

        }
        catch (IOException e) {
            System.out.println(e);
            return null;
        }
    }
    return customers;
}

@Override
public boolean addCustomer(Customer c) {
    customers.add(c);
    return this.saveCustomers();
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public boolean updateCustomer(Customer c) {
    Customer oldCustomer = this.getCustomer(c.getEmail());
    int i = customers.indexOf(oldCustomer);
    customers.remove(i);

    customers.add(i, c);

    return this.saveCustomers();
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public boolean deleteCustomer(Customer c) {
    customers.remove(c);
    return this.saveCustomers();
}

private boolean saveCustomers() {
    try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(customersFile)))){

        for (Customer customer : customers) {
            out.print(customer.getEmail() + "\t");
            out.print(customer.getFirstName() + "\t");
            out.println(customer.getLastName());

        }
        out.close();
        return true;

    }
    catch (IOException e) {
        return false;
    }



}

}

Im not certain if the problem is in the application or if it is in the textfile class

run: Welcome to the Customer Maintenance application

COMMAND MENU list - List all customers add - Add a customer del - Delete a customer help - Show this menu exit - Exit this application

list DEBUG LINE 1

Above was an example of the console output.

Why are you declaring a string inside the loop?

try this instead:

Scanner sc = new Scanner(System.in);
String userChoice;
do {
    displayMenu();
    userChoice = sc.nextLine(); //takes in the entire lien you type in
    System.out.println("DEBUG LINE 1");


    CustomerTextFile textFile = new CustomerTextFile();
    System.out.println("DEBUG LINE 2");
    performAction(userChoice, textFile);
    System.out.println("DEBUG LINE 3");
} while(keepGoing);

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM