Thursday, 4 July 2013

Java File Input Output Program

Java File Input Output Program

 Java Code:
import java.io.*;
import java.util.*;

/**
 *
 * @author saad
 */
public class run {

    public static void main(String[] args)
            throws FileNotFoundException {

        Scanner console = new Scanner(System.in);
        System.out.print("Input file: ");
        String inputFileName = console.next();
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter("D:\\saad\\eclipse\\ec\\13\\agentreport.txt", true));
        } catch (IOException e) {
        }
        try (PrintWriter o = new PrintWriter(out)) {
            Set<String> propertyTypes = pTypes(inputFileName);

            for (String type : propertyTypes) {
                System.out.println(type);
                o.println(type);
            }
            Set<String> Agent = agentValue(inputFileName);
            for (String tail : Agent) {
                {
                    System.out.println(tail);
                    o.println(tail);
                }
            }
            o.flush();
        }}
    public static Set<String> pTypes(String inputFileName)
            throws FileNotFoundException
    {
        Set<String> Saperate = new TreeSet<>();
        try (Scanner in = new Scanner(new File(inputFileName))) {
            in.useDelimiter("[1234567890.]");
            while (in.hasNext()) {
                boolean add = Saperate.add(in.next().toUpperCase());
            }}
        return Saperate;
    }
    public static Set<String> agentValue(String inputFileName)
            throws FileNotFoundException {
        TreeSet<String> d = new TreeSet<>();
        SortedMap<String, Number> agentValues = new TreeMap<>();
        Scanner in = new Scanner(new File(inputFileName));
        String line = inputFileName;
        while (in.hasNextLine()) {
            try {
                line = in.nextLine();
                String[] fields = line.split("[\\s}]");
                String agentId = (fields[3]);
                Double pValue = Double.parseDouble(fields[2]);
                if (agentValues.containsKey(agentId)) {
                    pValue += agentValues.get(agentId).doubleValue();
                }
                agentValues.put(agentId, pValue);
            } catch (Exception e) {
            }

            Set<String> keySet = agentValues.keySet();
            for (String key : keySet) {
                Number n = agentValues.get(key);
                d.add(key + ":" + n);
            }
        }
        return d;
    }
}

Snapshots:




No comments:

Post a Comment