简体   繁体   English

从文件读写问题

[英]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). 在第[75]行,bw.write(content)我正在写一个名为“ output.txt”的文件(我也想给我写文件的那些雇员加上时间戳)。 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. 因此,当我现在转到PC的E驱动器时,我只看到一个名为output.txt(最新修改时间)的文件,但其中没有任何内容。 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. 相反,您可以使用flush()方法来确保将内容写入文件中。

Consider reading the documentation at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html . 考虑阅读http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html上的文档。

In my test it works fine . 在我的测试中,它工作正常。 but change bw.close(); 但是改变bw.close(); to bw.flush(); 到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 . 马上,我建议尝试用E:\\output.txt替换您的文件名。 I believe windows file paths use backslashes. 我相信Windows文件路径使用反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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