在java中创建输出文件

时间:2016-05-01 22:07:23

标签: java

所以我已经完成了大约90%的代码,但我仍然坚持到最后一部分。所以我想将partNumber,quantity和toalCost从我的MainClass存储到我的OrdersProcessed类并生成一个输出文件。我该怎么做呢?我用我的代码发布的那个教程是一个很好的方法吗?

MainClass:

import java.util.Scanner;

public class MainClass
{

    private static final String DATA_FILE = "masterInventory.dat";
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        InventoryData myData;
        double price = 0.0;
        int quantity = 0;
        double totalCost = 0.0;
        int index = 0;
        int partNumber = 0;
        char runProgram;
        int totalFound;
        int partFound = 0;
        int partnotFound = 0;

        myData = new InventoryData(DATA_FILE);
        myData.loadArrays();
        myData.bubbleSort();

        System.out.println("Do you want to continue? prss 'Y' for yes or 'Q' to quit");
                runProgram = input.nextLine().charAt(0);
                runProgram = Character.toUpperCase(runProgram);


                while (runProgram == 'Y' || runProgram == 'Q')
                {

                    if(runProgram == 'Y')
                    {

                        System.out.print("Please enter your part number: "); 
                        partNumber = input.nextInt();

                        // TODO start your loop here

                        index = myData.binSearch(partNumber);

                        if(index != -1)
                        {
                            price = myData.getPrice(index);
                            System.out.printf("The price is %.2f%n", price);
                            System.out.print("How many would you like?");
                            quantity = input.nextInt();
                            totalCost = price * quantity;
                            partFound++;

                            // TODO do printing, writing to file here
                        }
                        else
                        {
                            System.out.println("Part not found");
                            partnotFound++;
                        }

                        System.out.println("Part# ");
                        System.out.print(partNumber);
                        System.out.println();

                        System.out.println("Price $");
                        System.out.print(price);
                        System.out.println();

                        System.out.println("Quantity ");
                        System.out.print(quantity);
                        System.out.println();

                        System.out.println("totalPrice ");
                        System.out.print(totalCost);
                        System.out.println();

                        System.out.println("Do you want to continue? prss 'Y' for yes or 'Q' to quit");
                        runProgram = input.next().charAt(0);
                        runProgram = Character.toUpperCase(runProgram);

                    }
                    if (runProgram == 'Q')
                    {
                        totalFound = partFound + partnotFound;

                        System.out.println("Total parts found : " + partFound);
                        System.out.println("Total parts not found : " + partnotFound);
                        System.out.println("Total parts searched : " + totalFound);

                        break;
                    }// end if 'Q'
                }// end while
    }
}

OrderProcessed Class:

public class OrdersProcessed
{





    public OrdersProcessed(String File)
    {
        File = "ordersProcessed.dat";
    }


    public void saveOneRecord()
    {

    }

然后这是我发现的教程:

public static void main(String[] args) 
{
    String lastName, firstName;
    double salary;

    try
    {
        //Instantiate a PrintWriter to append to an existing file
        PrintWriter myPW = new PrintWriter (new FileWriter("employeeOut.dat", true));
        Scanner myScanner = new Scanner (System.in);

        //Input first value for lastName, which will be the LCV
        System.out.println("Input the employee's last name (or Q to quit): ");
        lastName = myScanner.nextLine();

        while (!(lastName.equals("Q") || lastName.equals("q")))
        {
            System.out.println("Input the employee's first name: ");
            firstName = myScanner.nextLine();
            System.out.println("Input the employee's salary: ");
            salary = myScanner.nextDouble();
            myScanner.nextLine();   //Eliminate carriage return left in stream after numeric input

            //Save one record
myPW.printf ("%s %s %.2f\n", lastName, firstName, salary);

            //Input next last name
            System.out.println("Input the employee's last name (or Q to quit): ");
            lastName = myScanner.nextLine();
        }//END while

        myPW.close();
        myScanner.close();

    }//END try
    catch (IOException ex)
    {
        ex.printStackTrace();
    }
}//END main method

3 个答案:

答案 0 :(得分:0)

一开始我认为你想将partNumber,quantity和totalCost存储在一个文件中,下面的代码应该这样做:

PrintWriter writer = new PrintWriter("file_name.txt", "UTF-8");
writer.println(partNumber);
writer.println(quantity);
writer.println(toalCost);
writer.close();

但看起来您想要将partNumber,quantity和totalCost存储在OrdersProcessed类中并将其保存在文件中。

所以,首先让你的OrdersProcessed类实现Serializable:

public class OrdersProcessed implements Serializable {

使用setter方法将实例变量添加到OrdersProcessed类:

int quantity = 0;
int partNumber = 0;
double totalCost = 0.0;

将以下内容添加到saveOneRecord方法中:

  try
  {
     FileOutputStream fileOut = new FileOutputStream("ordersProcessed.dat");
     ObjectOutputStream out = new ObjectOutputStream(fileOut);
     out.writeObject(e);
     out.close();
     fileOut.close();
  } catch(IOException e)
  {
      e.printStackTrace();
  }

然后在" // TODO打印下面添加以下内容,在此处写入文件":

OrdersProcessed op = new OrdersProcessed();
op.setQuantity(quantity);
op.setPartNumber(partNumber);
op.setTotalCost(totalCost);
op.saveOneRecord();

有关序列化here的更多信息。

答案 1 :(得分:0)

您提供的教程确实显示了一种写入文件的简单方法。

如您所见,您需要创建一个PrintWriter对象(确保该文件存在):

PrintWriter myPW = new PrintWriter (new FileWriter("employeeOut.dat", true));

然后您可以使用printf在同一行上打印多个值。

myPW.printf ("%s %s %.2f\n", lastName, firstName, salary);

只要您可以访问打印作者和所需的值,就可以在任何地方使用它。在上面,3个值是lastName,firstName和salary,并且这些值被添加到第一个参数%s中的%.2f"%s %s %.2f\n"位,其中%s表示放置value为字符串,%.2f表示将值作为float放置到2位小数。您可以根据需要添加任意数量。有关详细信息,请参阅Java文档:https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#printf(java.lang.String,%20java.lang.Object...)

最后,您必须关闭PrintWriter对象:

myPW.close();

您可能需要使用try / catch语句来查找这些操作,以查找IOException。

答案 2 :(得分:0)

我没有看到你这样做的问题,但我确实看到了让你的代码更清洁的方法。你没有说你有任何错误,所以我假设它正常工作。

我从您的代码中删除了一些不必要的东西并进行了测试。一切正常

    public static void main(String[] args) 
    {
    String lastName = new String(), firstName;//Initialized lastName to prevent an error
    double salary;

    try
    {
        //Instantiate a PrintWriter to append to an existing file
        PrintWriter myPW = new PrintWriter (new FileWriter("employeeOut.dat", true));
        Scanner myScanner = new Scanner (System.in);

        //put all inputs inside the loop

        while (!(lastName.equals("Q") || lastName.equals("q")))
        {
            System.out.println("Input the employee's last name (or Q to quit): ");
            lastName = myScanner.nextLine();
            System.out.println("Input the employee's first name: ");
            firstName = myScanner.nextLine();
            System.out.println("Input the employee's salary: ");
            salary = myScanner.nextDouble();
            myScanner.nextLine();   //Eliminate carriage return left in stream after numeric input

            //Save one record
            myPW.printf ("%s %s %.2f\n", lastName, firstName, salary);

           //loops back to last name now

        }//END while

        myPW.close();
        myScanner.close();

    }//END try
    catch (IOException ex)
    {
        System.out.print(ex);
    }
}//END main method

}