简体   繁体   中英

Issue with writing and reading from file

I am in a situation where I want to write something(writing employee details with punchin & punchout) to a file and read it back(to show as a report of who all the employees punchedin & punchedout).

package Test;

 import java.io.*;
 import java.text.*;
 import java.util.*;
 public class Test {

public static void main(String[] args) throws IOException {
    String lastName = "";
    String firstName = "";
    String choice = "y";
    String customerChoice = "x";
    int empid = 0;
    Scanner sc = new Scanner(System.in);

    int currentIndex;

    File file = new File("E:/output.txt");
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    int[] punchedArray;
        punchedArray = new int[100];

   // System.out.println(t);
    while (!customerChoice.equalsIgnoreCase("d") && customerChoice != "invalid" && choice.equalsIgnoreCase("y")) {
        customerChoice = getValidCustomerChoice(sc);
        if (customerChoice.equalsIgnoreCase("a")) {
           // System.out.println("In Create Customer");
            System.out.print("Enter your first name: ");

                firstName = sc.next();
                System.out.print("Enter your last name: ");
                lastName = sc.next();
                System.out.println(firstName + lastName + "with employee id" + empid);
                //System.out.println(firstNameArray[newEmployeeIndex] + " " + lastNameArray[newEmployeeIndex] + " your employee ID is: " + employeeIDArray[newEmployeeIndex]);
                empid++;

            //sc.next();
        }
        if (customerChoice.equalsIgnoreCase("b")) {
            System.out.println("Welcome to the punch in/out screen"+"\n");
                System.out.print("Enter your employee ID: ");
                currentIndex = Integer.parseInt(sc.next());

                if (punchedArray[currentIndex] == 0)
                {
                    System.out.println("You are now punched in");
                    punchedArray[currentIndex] = 1;

                }
                else if (punchedArray[currentIndex] == 1)
                {
                    System.out.println("You are now punched out");
                    punchedArray[currentIndex] = 0;
                }
               System.out.print(firstName + " "+ lastName + " "+ "your employee ID is " + currentIndex + " and your clock date and time is: " + " "+ cal.getTime() +"\n");
               String content = firstName + lastName + empid + cal.getTime();
               bw.write(content);
               bw.newLine();
               bw.close();
        }

        if (customerChoice.equalsIgnoreCase("c")) {
            System.out.print("Welcome to the report screen." + "\n");
            System.out.print("Enter your selection (I = individual report or A= all employees):" + "\n");
            customerChoice = sc.next();
            if (customerChoice.equalsIgnoreCase("i")) {
                System.out.println("In Individual Report");
            } else if (customerChoice.equalsIgnoreCase("a")) {
                System.out.println("In Consoldated Report");
            }
        }
        if(customerChoice.equalsIgnoreCase("d"))
        {
        //bw.close();
            break;
        }

    }
}

public static String getValidCustomerChoice(Scanner sc) {
    String customerChoice = "";
    // sc.nextLine();

    boolean isValid = false;
    int invalidCounter = 0;
    System.out.print("Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):");
    while (isValid == false && invalidCounter < 3) {

        customerChoice = sc.next();
        if (!customerChoice.equalsIgnoreCase("a")
                && !customerChoice.equalsIgnoreCase("b") && !customerChoice.equalsIgnoreCase("c") && !customerChoice.equalsIgnoreCase("d") && !customerChoice.equalsIgnoreCase("I") && !customerChoice.equalsIgnoreCase("A")) {
            System.out.println("Invalid choice. Try again.\n");
            invalidCounter++;
        } else {
            isValid = true;
        }
        sc.nextLine();
    }
    if (invalidCounter >= 3) {
        System.out.println("Invalid three times. Program Exiting.\n");
        return "invalid";
    }
    return customerChoice;
}

}

At line[75] bw.write(content) I am writing to a file called "output.txt"(I also want to add timestamp to those employees whom I wrote to file). But somehow the data is not going into the file, I am sure that I am making a mistake somewhere in closing that and I want to read from the same file which I wrote. Can someone please suggest me where I am going wrong?

Adding more details:

    run:
    Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
    Enter your first name: Sa
    Enter your last name: Ka
    SaKawith employee id0
    Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
    Welcome to the punch in/out screen

    Enter your employee ID: 0
    You are now punched in
    Sa Ka your employee ID is 0 and your clock date and time is:  Sun Jun 08 20:19:42 EDT 2014
    Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
    Enter your first name: Ka
    Enter your last name: Ma
    KaMawith employee id1
    Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
    Welcome to the punch in/out screen

    Enter your employee ID: 1
    You are now punched in
    Ka Ma your employee ID is 1 and your clock date and time is:  Sun Jun 08 20:19:42 EDT 2014
    Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):c
    Welcome to the report screen.
    Enter your selection (I = individual report or A= all employees):
    a
    In Consoldated Report
    Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):BUILD STOPPED (total time: 1 minute 8 seconds)

So,when I go now to E drive of my Pc I just see a file named output.txt(latest modified time) but there's nothing in it. I tried to close my buffer after the loop but no luck with it. Also, Please advise on reading the data which I wrote to the file

Please advise!

Thanks

I'm not sure if I understand your issue, but like this, you can only write to the file once, since you close it after writing to it. Instead, you can use the flush() method to ensure the contents are written to the file.

Consider reading the documentation at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html .

In my test it works fine . but change bw.close(); to bw.flush(); Because the outputstream will be closed after first input. and att second input you got an exception

Right off the bat I'd suggest trying to replace your file name with E:\\output.txt . I believe windows file paths use backslashes.

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