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, Charset charset) throws IOException 

Source Link

Document

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

Usage

From source file:assignment.HTTPResponse.java

public void serve(HTTPRequest httpRequest, OutputStream outputStream, Socket socket)
        throws IOException, ParseException, InterruptedException {
    PrintWriter pw = new PrintWriter(outputStream, true);
    JSONObject obj = new JSONObject();
    if (httpRequest.getHttpMethod().equals("GET")) {

        String[] url = (httpRequest.getResourceURI()).split("\\?");
        if (url[0].equals("/request")) {
            String ar1[] = url[1].split("&");
            String[] name1 = ar1[0].split("=");
            String connId = name1[1];
            String[] name2 = ar1[1].split("=");
            int timeout = Integer.parseInt(name2[1]);
            input[i][0] = connId;/*from w  ww .j ava2  s  . com*/

            Date startTime = new Date();
            Date parsedDate = df.parse(startTime.toString());
            Date endTime = new Date(parsedDate.getTime() + (1 * timeout));
            input[i][1] = startTime.toString();
            input[i][2] = endTime.toString();
            i++;

            obj.put("status", "ok");
            try {
                Thread.currentThread().sleep(timeout);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            pw.println(obj);
        } else if (url[0].equals("/serverStatus")) {
            Date now = new Date();
            long newDateTime = df.parse((new Date()).toString()).getTime();

            String result = "";
            JSONArray ja = new JSONArray();
            for (int j = 0; j < input.length; j++) {
                if (input[j][0] != null) {
                    Date end = df.parse(input[j][2]);
                    if (end.compareTo(now) > 0) {
                        long endDateTime = (df.parse(input[j][2])).getTime();
                        long diff = ((endDateTime - newDateTime) / 1000);
                        JSONObject obj1 = new JSONObject();
                        obj1.put(input[j][0], diff);
                        result += obj1;
                    }
                }
            }
            pw.println(result);
        } else {
            pw.println("Request not supported.");
        }
    } else if ((httpRequest.getHttpMethod().equals("PUT")) || (httpRequest.getHttpMethod().equals("POST"))) {
        if (httpRequest.getResourceURI().equals("/kill")) {
            boolean found = false;
            Date now = new Date();
            for (int j = 0; j < input.length; j++) {
                if (input[j][0] != null && input[j][0].equals(httpRequest.getBody())) {
                    Date end = df.parse(input[j][2]);
                    if (end.compareTo(now) > 0) {
                        input[j][2] = now.toString();
                        found = true;
                    }
                }
            }
            if (found) {
                obj.put("status", "killed");
            } else {
                obj.put("status", "Invalid connId " + httpRequest.getBody());
            }
            System.out.println(obj);
            pw.println(obj);
        } else {
            pw.println("Request not supported.");
        }
    }
    socket.close();
}

From source file:de.tudarmstadt.ukp.dkpro.c4corpus.boilerplate.standalone.HTMLBoilerplateRemoval.java

public static void processHtmlFile(File input, File outFile, boolean keepMinimalHtml) throws IOException {
    // read the html file
    String html = FileUtils.readFileToString(input, "utf-8");

    // boilerplate removal
    String cleanText;/*from www.ja  v a  2  s .  c o  m*/
    if (keepMinimalHtml) {
        cleanText = boilerPlateRemoval.getMinimalHtml(html, null);
    } else {
        cleanText = boilerPlateRemoval.getPlainText(html, null);
    }

    // write to the output file
    PrintWriter writer = new PrintWriter(outFile, "utf-8");
    writer.write(cleanText);

    writer.close();
}

From source file:net.socket.bio.TimeServerHandler.java

@Override
public void run() {
    BufferedReader in = null;//from w ww.ja  va  2s. co  m
    PrintWriter out = null;
    try {
        InputStream ins = this.socket.getInputStream();
        in = new BufferedReader(new InputStreamReader(ins));
        out = new PrintWriter(this.socket.getOutputStream(), true);
        String currentTime = null;
        String body = null;
        while (true) {

            body = in.readLine();
            if (body == null)
                break;
            System.out.println("The time server receive order : " + body);
            currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
                    ? new java.util.Date(System.currentTimeMillis()).toString()
                    : "BAD ORDER";
            out.println(currentTime);
        }
    } catch (Exception e) {
        e.printStackTrace();//in read exception can resolve by ready?
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(this.socket);
    }
}

From source file:gomoku.aneh.MainForm.java

/**
 * Creates new form main/*www  . j  a  v a2  s  .com*/
 */
public MainForm() {

    try {
        socket = new Socket("127.0.0.1", 8080);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = socket.getInputStream();

    } catch (UnknownHostException e) {
        System.out.println("Unknown host");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("No I/O");
        System.exit(1);
    }

    new Thread(new listenner(this));

    out.print("GET /\nSec-WebSocket-Key: abcdefghij\n\n");
    out.flush();

    initComponents();

    setLayout(new BorderLayout());
    panel = new JPanel();
    panel.setLayout(null);
    add(panel);
    boardButton = new JButton[20][20];
    for (int i = 0; i < 20; i++)
        for (int j = 0; j < 20; j++) {
            boardButton[i][j] = new JButton("");
            boardButton[i][j].setBounds(i * 20 + 10, j * 20 + 70, 20, 20);
            panel.add(boardButton[i][j]);
        }
}

From source file:IBDMUT.Tools.java

public static void initLog(String logFile) throws FileNotFoundException, UnsupportedEncodingException {
    setLogFileStream(new PrintWriter(logFile, "UTF-8"));
}

From source file:net.sf.jsptest.compiler.jsp20.mock.MockJspWriter.java

public MockJspWriter() {
    super(1024, true);
    log = LogFactory.getLog(getClass());
    stringWriter = new StringWriter();
    writer = new PrintWriter(stringWriter, true);
}

From source file:ExecutorHttpd.java

public void run() {
    try {/*from  www. j  a  v  a  2s  . com*/
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), "8859_1"));
        OutputStream out = client.getOutputStream();
        PrintWriter pout = new PrintWriter(new OutputStreamWriter(out, "8859_1"), true);
        String request = in.readLine();
        System.out.println("Request: " + request);

        byte[] data = "hello".getBytes();
        out.write(data, 0, data.length);
        out.flush();
        client.close();
    } catch (IOException e) {
        System.out.println("I/O error " + e);
    }
}

From source file:ir.ac.ut.snl.mrcd.InputConverter.java

public void convert(String filename) throws FileNotFoundException, UnsupportedEncodingException {
    int paddingSize = 49; //  50-1; 1 baraye '\n'

    File file = new File(filename);
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    Scanner scanner = new Scanner(bufferedReader);

    PrintWriter printWriter = new PrintWriter(filename + "-converted", "UTF-8");

    int n = scanner.nextInt();
    scanner.nextLine();/*www . j  av a 2s  . c o m*/

    printWriter.write(StringUtils.leftPad(String.valueOf(n), paddingSize));
    printWriter.write('\n');

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        printWriter.write(StringUtils.leftPad(line, paddingSize));
        printWriter.write('\n');
    }

    scanner.close();
    printWriter.close();
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7bConvArgRankProducer.java

@SuppressWarnings("unchecked")
public static void prepareData(String[] args) throws Exception {
    String inputDir = args[0];/*from www  .  j a v a  2  s  .c  om*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    List<File> files = IOHelper.listXmlFiles(new File(inputDir));

    // take only the gold data for this task
    String prefix = "all_DescendingScoreArgumentPairListSorter";
    Iterator<File> iterator = files.iterator();
    while (iterator.hasNext()) {
        File file = iterator.next();

        if (!file.getName().startsWith(prefix)) {
            iterator.remove();
        }
    }

    int totalArgumentsCounter = 0;

    DescriptiveStatistics statsPerTopic = new DescriptiveStatistics();

    for (File file : files) {
        List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream()
                .fromXML(file);

        String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", "");

        PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8");
        pw.println("#id\trank\targument");

        Graph graph = buildGraphFromPairs(argumentPairs);

        Map<String, Argument> arguments = collectArguments(argumentPairs);

        int argumentsPerTopicCounter = arguments.size();

        PageRank pageRank = new PageRank();
        pageRank.setVerbose(true);
        pageRank.init(graph);

        for (Node node : graph) {
            String id = node.getId();
            double rank = pageRank.getRank(node);

            System.out.println(id);

            Argument argument = arguments.get(id);

            String text = Step7aLearningDataProducer.multipleParagraphsToSingleLine(argument.getText());

            pw.printf(Locale.ENGLISH, "%s\t%.5f\t%s%n", argument.getId(), rank, text);
        }

        totalArgumentsCounter += argumentsPerTopicCounter;
        statsPerTopic.addValue(argumentsPerTopicCounter);

        pw.close();
    }

    System.out.println("Total gold arguments: " + totalArgumentsCounter);
    System.out.println(statsPerTopic);
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestDPMeans.java

public static void genTestData(int k) {
    PrintWriter writer;/*from  w  ww .  ja v  a 2 s. co  m*/
    try {
        writer = new PrintWriter("test.txt", "UTF-8");

        // each class size is equal 
        int classSize = 1000000 / k;

        double stdDev = 30.0;

        // generate k classes of data points using a normal distribution with random means and fixed std deviation
        for (int i = 0; i < k; i++) {
            Random rnd = new Random();

            double meanLat = rnd.nextDouble() * 400.0;
            double meanLon = rnd.nextDouble() * 400.0;

            // randomly generate a dataset of lat, lon points
            for (int j = 0; j < classSize; j++) {
                double x = rnd.nextGaussian() * stdDev + meanLat;
                double y = rnd.nextGaussian() * stdDev + meanLon;

                writer.println(x + "," + y);
            }
        }
        writer.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}