写入后文本文件为空。获取indexOutOfBound

时间:2013-12-04 23:36:50

标签: java file-io

代码要求用户输入itemName,price和quantity。我看到它创建了一个文件,但里面没有字符串?缓冲区有问题吗?提前谢谢,

userInput: 输入项目名称:item1 输入商品价格$ 14 输入商品数量:3 你想要另一件商品吗?是(y)或否(n)n

代码:

while(userInput.charAt(0)!='n'){
    System.out.print("Enter item name: ");
    itemName = kybd.nextLine();
    PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

    System.out.print("Enter item price $");
    price = kybd.nextLine();
    PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

    System.out.print("Enter item quantity: ");
    quantity = kybd.nextLine();
    PrintWriter out2 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));


    System.out.print("Do you want another item? Yes(y) or No(n)");
    userInput= kybd.next();
    }//end of whileLoop

编辑后仍然相同 - 文件中没有字符串:

while(userInput.charAt(0)!='n'){
        PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

    System.out.print("Enter item name: ");
    itemName = kybd.nextLine();
    out0.println(itemName);

update2:确定所以最后是冲洗结果out0.flush();我的输出是:item1 // nextline,price // nextline,quantity // nextLine ...我怎么能让它保持在同一条线上,以便我以后可以用hasNext做一些操作?

UPDATE3: 获取indexOutOfBound。成功保存文件后。我打开文件来执行以下任务:找到total costPerItem,totalCount和sum。不知道我为什么离开了界限。错误指出 totalCost = + Double.parseDouble(index [1] .trim()); 源代码:

Scanner data = new Scanner(new File("registryCopy.txt"));

    while(data.hasNext()){
        String line = data.nextLine();
        System.out.println(line);

        String[] index = line.split("\\t");
        totalCost += Double.parseDouble(index[1].trim());
        totalCount += Integer.parseInt(index[2].trim());

        sum = totalCost/totalCount;

    }

1 个答案:

答案 0 :(得分:4)

你不是写这个:

PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

(或其他2位作家),但只是准备好写作。尝试写入并冲洗/关闭它。

查看this SO question/answer以获取有关如何写入文件的更多信息。