无法将相同格式的控制台输出打印到文本文档中

时间:2013-09-30 21:35:10

标签: java file filewriter

我将我的java文件设置为计算电话帐单并以此格式打印到控制台。

Invoice
--------------------------
Account   Amount Due 
10011      $12.25
10033      $11.70
--------------------------
Total      $23.95

但是当我运行程序时,我只在文本文件

上得到这个
Account Amount_Due
10011 $12.25
10033 $11.7

有人可以帮我编辑正确格式的文件创建代码吗?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;


public class PhoneBill {
    Vector data;
    Vector processed = new Vector();

    Vector markProcessed = new Vector();
    public void readFile(String inFileStr)
    {
        String str = "";
        data = new Vector<LineItem>();
        FileReader fReader;
        InputStream inFileStream;
         try{
        fReader = new FileReader(inFileStr);
            BufferedReader br=new BufferedReader(fReader);
            String line;
            while ((line=br.readLine())!= null){
                if (line.indexOf("_") != -1)
                    continue;
                else
                  if (!line.isEmpty()){
                    data.add(new LineItem(line.trim()));

                  }
            }

            br.close(); 
        }       
        catch (Exception e){

        }
    }
    public void processCharges()
    {
        String out = "Account Amount_Due\n";
        System.out.println ("Invoice");
        System.out.println ("--------------------------");
        System.out.println ("Account   " + "Amount Due ");
        double total = 0.0;
        double lCharges =0;
        boolean done = false;
        DecimalFormat numFormatter = new DecimalFormat("$##.##");
        for (int j = 0; j < data.size(); j++ ){
            LineItem li =  (LineItem)data.get(j);
            String accNum = li.getAccountNum();
            if (j > 0){
                done = checkProcessed(accNum);}
            else
                processed.add(accNum);
            if (!done){
                   lCharges = 0;
            for (int i = 0; i < data.size(); i++){
              String acc = ((LineItem)data.get(i)).getAccountNum();
              if (acc.equals(accNum) && !done)
              lCharges += processItemCharges(accNum);
              done = checkProcessed(accNum);
            }
            lCharges+=10.0;
            System.out.format ("%s" + "      $%.2f%n",accNum, lCharges);
            out += accNum+" ";
            out += numFormatter.format(lCharges)+"\n";
            processed.add(accNum);

             total += lCharges;
            }

        }

        System.out.println ("--------------------------");
        System.out.format ("%s" + "      $%.2f%n","Total", total);
        writeToFile("invoice.txt", out);

    }
    private void writeToFile(String filename,String outStr)
    {
        try{
            File file = new File(filename);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(outStr);
            bw.close();

        } catch (IOException ioe){
            System.out.println(ioe.getMessage());
        }

    }
    private boolean checkProcessed(String accNum){
        if (processed.contains(accNum))
            return true;
        else
            return false;
    }


    private double processItemCharges(String accNum)
    {
        double charges = 0.0;

        for (int i = 0; i < data.size(); i++)
        {
            if(((LineItem)data.get(i)).getAccountNum().equals(accNum))
                charges += ((LineItem)data.get(i)).getCharges();
        }
        return charges;
    }
    public static void main(String[] args)
    {
        PhoneBill pB =  new PhoneBill();
        pB.readFile("input_data.txt");
        pB.processCharges();
    }

    class LineItem{
        String accNum ;
        String timeOfCall;
        double mins;
        double amountDue;
        boolean counted = false;

        public LineItem(String accStr)
        {
            processAccount(accStr);
        }

        private void processAccount(String accStr){
            StringTokenizer st = new StringTokenizer(accStr);
            accNum = (String)st.nextElement();
            timeOfCall = (String) st.nextElement();
            mins = Double.parseDouble((String) st.nextElement());
            if (timeOfCall.compareTo("08:00")>0 && timeOfCall.compareTo("22:00")<0)
                amountDue = mins*0.10;
            else
                amountDue = mins*0.05;
        }

        public String getAccountNum()
        {
            return accNum;
        }

        public double getCharges()
        {
            return amountDue;
        }

    }
}

2 个答案:

答案 0 :(得分:0)

打印到控制台(即System.out.println)与连接out变量(即out + =)不同。

所以当你打电话

writeToFile("invoice.txt", out);

您只是将字符串'out'中的内容写入文件。如果你回顾一下你的代码,你会发现所有缺失的行只会被打印到控制台,但不能连接到'out'变量。纠正这一点,你不应该有问题。

答案 1 :(得分:0)

研究这个。它使用了更高级的Java,但理解它将非常适合您。

package test;

import java.io.*;
import java.util.*;

public class PhoneBill {

    private static String BILL_FORMAT = "%-10s $%,6.2f\n";
    private static boolean DEBUG=true;

    Map<String, List<LineItem>> accounts = new HashMap<String,List<LineItem>>();

    public void readFile(String inFileStr) {
        FileReader fReader=null;
        try {
            fReader = new FileReader(inFileStr);
            BufferedReader br = new BufferedReader(fReader);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.indexOf("_") != -1)
                    continue;
                else if (!line.isEmpty()) {
                    LineItem li = new LineItem(line.trim());
                    List<LineItem> list = accounts.get(li.accNum);
                    if(list==null){
                        list = new ArrayList<LineItem>();
                        accounts.put(li.accNum, list);
                    }
                    list.add(li);
                }
            }

            br.close();
        } catch (Exception e) {
            /* Don't just swallow Exceptions. */
            e.printStackTrace();
        } finally { 
            if(fReader!=null){
                try{
                    fReader.close();
                } catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public void processCharges() {
        StringBuffer out = new StringBuffer(100)
            .append("Invoice\n")
            .append("--------------------------\n")
            .append("Account   Amount Due \n");
        double total = 0.0;
        double lCharges = 0;

        for (String accNum:accounts.keySet()) {
            List<LineItem> account = accounts.get(accNum);
            lCharges = 10;
            for(LineItem li:account){
                lCharges += li.getCharges();
            }
            total += lCharges;
            out.append(String.format(BILL_FORMAT, accNum, lCharges));
        }

        out.append("--------------------------\n");
        out.append(String.format(BILL_FORMAT, "Total", total));
        writeToFile("invoice.txt", out.toString());

    }

    private void writeToFile(String filename, String outStr) {
        if(DEBUG){
            System.out.printf("========%swriteToFile:%s=========\n", '=', filename);
            System.out.println(outStr);
            System.out.printf("========%swriteToFile:%s=========\n", '/', filename);
        }
        try {
            File file = new File(filename);

            // If file doesn't exist, then create it.
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(outStr);
            bw.close();

        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }

    }

    public static void main(String[] args) {
        PhoneBill pB = new PhoneBill();
        pB.readFile("input_data.txt");
        pB.processCharges();
    }

    static class LineItem {
        String accNum;
        double timeOfCall;
        double mins;
        double amountDue;
        boolean counted = false;

        private static final double EIGHT_AM = convertTime("08:00");
        private static final double TEN_PM = convertTime("22:00");

        public LineItem(String accStr) {
            processAccount(accStr);
        }

        private void processAccount(String accStr) {
            StringTokenizer st = new StringTokenizer(accStr);
            accNum = st.nextToken();
            timeOfCall = convertTime(st.nextToken());
            mins = Double.parseDouble(st.nextToken());
            if (timeOfCall > EIGHT_AM && timeOfCall < TEN_PM)
                amountDue = mins * 0.10;
            else
                amountDue = mins * 0.05;
        }

        public String getAccountNum() {
            return accNum;
        }

        public double getCharges() {
            return amountDue;
        }

        private static double convertTime(String in){
            /* Will blow up if `in` isn't given in h:m. */
            String[] h_m = in.split(":");
            return Double.parseDouble(h_m[0])*60+Double.parseDouble(h_m[1]);
        }

    }
}