public void speak(String txt) {
    try {
      Runtime rtime = Runtime.getRuntime();

      // start unix shell
      Process child = rtime.exec("/bin/sh");
      // or "/bin/sh set -t" to auto-exit after 1 command

      BufferedWriter outCommand =
          new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));

      // run a command
      outCommand.write("echo '" + txt + "' | festival --tts\n");
      outCommand.flush();

      // exit the unix shell
      outCommand.write("exit" + "\n");
      outCommand.flush();

      int wait = child.waitFor();
      System.out.println("exit code: " + wait);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private void passivate(BufferedWriter writer, HashMap<String, List<String>> idx)
      throws IOException {
    StringBuilder bldr = new StringBuilder();
    int ctr = 0;
    List<String> value;
    TreeMap<String, List<String>> map = new TreeMap<String, List<String>>(idx);
    for (Entry<String, List<String>> etr : map.entrySet()) {
      value = etr.getValue();
      bldr.append(etr.getKey()).append("/").append(value.size()).append(":");
      bldr.append(asString(value));
      bldr.append("#");
      ctr++;

      if (ctr % 1000 == 0) {
        writer.write(bldr.toString());
        writer.newLine();
        bldr.delete(0, bldr.length());
        writer.flush();
      }
    }

    writer.write(bldr.toString());
    bldr.delete(0, bldr.length());
    writer.newLine();
    writer.flush();
    writer.close();
    idx.clear();
    idx = null;
    map.clear();
    map = null;
  }
 private void writeHistory(int historyNum) throws IOException {
   if (historyNum <= MAX_HISTORY_ENTRIES) {
     File historyFile = getHistoryFile(false);
     BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile));
     try {
       for (String historyEntry : history) {
         writer.write(historyEntry);
         writer.newLine();
       }
     } finally {
       writer.flush();
       writer.close();
     }
   } else {
     File historyFile = getHistoryFile(false);
     BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile));
     try {
       for (String historyEntry :
           history.subList(historyNum - MAX_HISTORY_ENTRIES - 1, historyNum - 1)) {
         writer.write(historyEntry);
         writer.newLine();
       }
     } finally {
       writer.flush();
       writer.close();
     }
   }
 }
  private void assertIsBrowse(Socket httpSock, int port) throws IOException {
    // start reading and confirming the HTTP request
    String currLine = null;
    BufferedReader reader =
        new BufferedReader(
            new InputStreamReader(httpSock.getInputStream(), HTTP.DEFAULT_PROTOCOL_CHARSET));

    // confirm a GET/HEAD push proxy request
    currLine = reader.readLine();
    assertEquals("GET / HTTP/1.1", currLine);

    // make sure the node sends the correct Host val
    currLine = reader.readLine();
    assertTrue(currLine.startsWith("Host:"));
    StringTokenizer st = new StringTokenizer(currLine, ":");
    assertEquals(st.nextToken(), "Host");
    // this assertion fails when localhost is bound to multiple IP addresses
    // since the client might connect to a different address than the server
    // socket is listening on
    InetAddress.getByName(st.nextToken().trim());
    // assertEquals(InetAddress.getByName(st.nextToken().trim()), addr);
    assertEquals(port, Integer.parseInt(st.nextToken()));

    // send back a 200 and make sure no PushRequest is sent via the normal
    // way
    BufferedWriter writer =
        new BufferedWriter(
            new OutputStreamWriter(httpSock.getOutputStream(), HTTP.DEFAULT_PROTOCOL_CHARSET));

    writer.write("HTTP/1.1 200 OK\r\n");
    writer.flush();
    writer.write("\r\n");
    writer.flush();
    // TODO: should i send some Query Hits? Might be a good test.
  }
Example #5
0
 void close() {
   if (connection != null) {
     try {
       connection.close();
       log.write("Connection closed\n");
       log.flush();
     } catch (Exception e) {
       try {
         log.write("Cannot close connection to the DB\n");
         log.write(e.toString());
         log.flush();
       } catch (IOException ie) {
         System.out.println(ie.toString());
       }
     }
   }
   try {
     out.close();
   } catch (Exception e) {
     try {
       log.write("Cannot close file\n");
       log.write(e.toString());
       log.flush();
     } catch (IOException ie) {
       System.out.println(ie.toString());
     }
   }
 }
  public void processCommand(String cmd, User user) {

    java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(cmd);

    try {
      String book, command = null;
      book = tokenizer.nextToken(" ");
      if (tokenizer.hasMoreTokens()) command = tokenizer.nextToken(" ");
      output.write(cmd + "\n");
      output.flush();

      Book b = (Book) bookMap.get(book);
      if (b == null) {
        output.write("invalid com.library.bo.book : " + book + "\n");
        output.flush();
        return;
      } else if (command != null) b.execute(command, user);
      else output.write(b.getTitle() + "\n");
      output.write("System> OK\n");
      output.flush();

    } catch (IOException e) {
      e.printStackTrace();
    } catch (InvalidActionException e) {
      try {
        output.write("System> " + e.getMessage() + "\n");
        output.flush();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
Example #7
0
 public static void write(StringBuffer content) {
   try {
     // Create file
     FileWriter fstreamECF = new FileWriter(localjsECFFilePath);
     BufferedWriter outECF = new BufferedWriter(fstreamECF);
     outECF.write(content.toString());
     outECF.flush();
     // Close the output stream
     outECF.close();
     fstreamECF.close();
     FileWriter fstreamMAC = new FileWriter(localjsMACFilePath);
     BufferedWriter outMAC = new BufferedWriter(fstreamMAC);
     outMAC.write(content.toString());
     outMAC.flush();
     // Close the output stream
     outMAC.close();
     fstreamMAC.close();
     FileWriter fstreamDelayedLDAP = new FileWriter(localjsDelayedLDAPFilePath);
     BufferedWriter outDelayedLDAP = new BufferedWriter(fstreamDelayedLDAP);
     outDelayedLDAP.write(content.toString());
     outDelayedLDAP.flush();
     // Close the output stream
     outDelayedLDAP.close();
     fstreamDelayedLDAP.close();
   } catch (Exception e) {
     // Catch exception if any
     log.error("Error: " + e.getMessage());
   }
 }
Example #8
0
 // 合并file1和file2,返回合并后的文件名
 public static File mergeTwoFile(File file1, File file2) throws Exception {
   BufferedReader br1 = new BufferedReader(new FileReader(file1));
   BufferedReader br2 = new BufferedReader(new FileReader(file2));
   // 创建合并后的文件
   String resultFileName = "E:\\dsaa\\" + System.currentTimeMillis() + ".txt";
   File resultFile = new File(resultFileName);
   while (resultFile.exists()) {
     resultFileName = "E:\\dsaa\\" + System.currentTimeMillis() + ".txt";
     resultFile = new File(resultFileName);
   }
   BufferedWriter bw = new BufferedWriter(new FileWriter(resultFileName));
   // 归并排序,且每读10次,将内存中的数据刷到磁盘
   int num1 = 0, num2 = 0, cnt = 0;
   String str1 = br1.readLine();
   String str2 = br2.readLine();
   cnt += 2;
   while (str1 != null && str2 != null) {
     num1 = Integer.valueOf(str1);
     num2 = Integer.valueOf(str2);
     if (num1 > num2) {
       bw.write(Integer.valueOf(str2) + "\r\n");
       str2 = br2.readLine();
       cnt++;
       if (cnt == 9) {
         cnt = 0;
         bw.flush();
       }
     } else {
       bw.write(Integer.valueOf(str1) + "\r\n");
       str1 = br1.readLine();
       cnt++;
       if (cnt == 9) {
         cnt = 0;
         bw.flush();
       }
     }
   }
   while (str1 != null) {
     bw.write(Integer.valueOf(str1) + "\r\n");
     str1 = br1.readLine();
     cnt++;
     if (cnt == 9) {
       cnt = 0;
       bw.flush();
     }
   }
   while (str2 != null) {
     bw.write(Integer.valueOf(str2) + "\r\n");
     str2 = br2.readLine();
     cnt++;
     if (cnt == 9) {
       cnt = 0;
       bw.flush();
     }
   }
   br1.close();
   br2.close();
   bw.close();
   return resultFile;
 }
Example #9
0
  public void chat() throws UnknownHostException, IOException {
    Socket socket = new Socket("localhost", 33333);

    Reader masukan = null;
    BufferedReader masukanBuff = null;
    int a = 0;
    try {
      for (; ; ) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Perintah (SIAPA / WAKTU / WAKTU N --> N Integer): ");
        String ketikanSatuBaris = keyboard.nextLine();

        // Tulis ke socket
        Writer keluaranWriter = new OutputStreamWriter(socket.getOutputStream());
        BufferedWriter keluaranBuff = new BufferedWriter(keluaranWriter);
        keluaranBuff.write(ketikanSatuBaris);
        keluaranBuff.write("\n");
        keluaranBuff.flush();

        // Baca dari Server
        System.out.print("Dari server: ");
        masukan = new InputStreamReader(socket.getInputStream());
        masukanBuff = new BufferedReader(masukan);
        String baris = masukanBuff.readLine();
        System.out.println(baris);
        if (baris.equals("SIAPA")) {
          masukan = new InputStreamReader(socket.getInputStream());
          masukanBuff = new BufferedReader(masukan);
          baris = masukanBuff.readLine();

          keluaranBuff.write(ketikanSatuBaris);
          keluaranBuff.write("\n");
          keluaranBuff.flush();
          break;
        } else if (baris.equals("WAKTU")) {
          masukan = new InputStreamReader(socket.getInputStream());
          masukanBuff = new BufferedReader(masukan);
          baris = masukanBuff.readLine();

          keluaranBuff.write(ketikanSatuBaris);
          keluaranBuff.write("\n");
          keluaranBuff.flush();
          break;
        } else {
          masukan = new InputStreamReader(socket.getInputStream());
          masukanBuff = new BufferedReader(masukan);
          baris = masukanBuff.readLine();

          keluaranBuff.write(ketikanSatuBaris);
          keluaranBuff.write("\n");
          keluaranBuff.flush();
          break;
        }
      }
    } catch (IOException salah) {
      System.out.println(salah);
    } finally {
      if (socket != null) socket.close();
    }
  }
Example #10
0
 public void save() {
   if (!modified) return;
   BufferedWriter bwriter = null;
   FileWriter fwriter = null;
   try {
     if (!file.exists()) file.createNewFile();
     fwriter = new FileWriter(file);
     bwriter = new BufferedWriter(fwriter);
     for (Entry<String, PropertiesEntry> entry : map.entrySet()) {
       StringBuilder builder = new StringBuilder();
       builder.append(entry.getKey());
       builder.append(" = ");
       builder.append(entry.getValue().value);
       bwriter.write(builder.toString());
       bwriter.newLine();
     }
     bwriter.flush();
   } catch (IOException e) {
     Jail.log.log(Level.SEVERE, "[Jail]: IO Exception with file " + file.getName());
   } finally {
     try {
       if (bwriter != null) {
         bwriter.flush();
         bwriter.close();
       }
       if (fwriter != null) {
         fwriter.close();
       }
     } catch (IOException e) {
       Jail.log.log(
           Level.SEVERE, "[Jail]: IO Exception with file " + file.getName() + " (on close)");
     }
   }
 }
 public void writeGrams(String storageFile, Map<String, HashSet<String>> map) {
   int count = 0;
   try {
     BufferedWriter writer =
         new BufferedWriter(new OutputStreamWriter(new FileOutputStream(storageFile)));
     StringBuilder string = new StringBuilder();
     for (Map.Entry<String, HashSet<String>> set : map.entrySet()) {
       count++;
       string.append(set.getKey().trim()).append(":");
       string.append(set.getValue().toString());
       string.append("#");
       if (count == 10000) {
         writer.write(string.toString());
         writer.newLine();
         string = new StringBuilder();
         writer.flush();
         count = 0;
       }
     }
     writer.write(string.toString());
     writer.flush();
     writer.close();
     map.clear();
     map = null;
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
    private boolean safeEquals(final ClasspathItemWrapper a, final ClasspathItemWrapper b) {
      try {
        final StringWriter as = new StringWriter();
        final StringWriter bs = new StringWriter();

        final BufferedWriter bas = new BufferedWriter(as);
        final BufferedWriter bbs = new BufferedWriter(bs);

        weaken(a).write(bas);
        weaken(b).write(bbs);

        bas.flush();
        bbs.flush();

        as.close();
        bs.close();

        final String x = as.getBuffer().toString();
        final String y = bs.getBuffer().toString();

        return x.equals(y);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
Example #13
0
 void connect() {
   try {
     String file = "logdataDB.txt";
     fstream = new FileWriter(file, true);
     out = new BufferedWriter(fstream);
   } catch (Exception e) {
     try {
       log.write("Cannot open file\n");
       log.write(e.toString());
       log.flush();
     } catch (IOException ie) {
       System.out.println(ie.toString());
     }
   }
   try {
     log.write("Connecting...\n");
     String url =
         "jdbc:mysql://" + Properties.HOST + ":" + Properties.PORT + "/" + Properties.DATABASE;
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     connection = DriverManager.getConnection(url, Properties.USER, Properties.PASSWORD);
     log.write("Connection established\n");
     log.flush();
   } catch (Exception e) {
     try {
       log.write("Cannot connect to the DB\n");
       log.write(e.toString());
       log.flush();
     } catch (IOException ie) {
       System.out.println(ie.toString());
     }
   }
 }
 public void run() {
   while (true) {
     try {
       List<String> tList = null;
       if (cachedErrList.size() != 0) {
         synchronized (lock) {
           tList = cachedErrList;
           cachedErrList = new ArrayList<String>();
         }
         bfw = getBufferedWriter();
         for (int i = 0; i < tList.size(); i++) {
           bfw.write(tList.get(i));
           bfw.newLine();
         }
         bfw.flush();
       }
     } catch (Exception e) {
       LogFactory.getLogger(LogFactory.SYS_ERROR_LOG).error("写错误日志文件失败", e);
     } finally {
       try {
         bfw.flush();
       } catch (Exception e) {
         LogFactory.getLogger(LogFactory.SYS_ERROR_LOG).error("写错误日志文件失败", e);
       }
       try {
         Thread.sleep(Log2FileConf.recordInterval * 1000);
       } catch (InterruptedException e) {
         LogFactory.getLogger(LogFactory.SYS_ERROR_LOG).error("WriteErrFileThread", e);
       }
     }
   }
 }
 public void write(String storageFile, Map<String, ArrayList<Integer>[]> map, int... content) {
   int count = 0;
   try {
     BufferedWriter writer =
         new BufferedWriter(new OutputStreamWriter(new FileOutputStream(storageFile)));
     StringBuilder string = new StringBuilder();
     for (Map.Entry<String, ArrayList<Integer>[]> set : map.entrySet()) {
       count++;
       string.append(set.getKey().trim()).append(":");
       string.append(set.getValue()[0].toString()).append(":");
       string.append(set.getValue()[1].toString()).append(":");
       if (content[0] == 1) {
         string.append(set.getValue()[2].toString()).append(":");
         string.append(set.getValue()[3].toString());
       } else string.append(set.getValue()[2].toString());
       string.append("#");
       if (count == 10000) {
         writer.write(string.toString());
         writer.newLine();
         string = new StringBuilder();
         writer.flush();
         count = 0;
       }
     }
     writer.write(string.toString());
     writer.flush();
     writer.close();
     map.clear();
     map = null;
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  private void createFile(String text, File fos) {
    BufferedWriter out = null;
    try {
      out = new BufferedWriter(new FileWriter(fos));
      String begin =
          "<html>"
              + "<head>"
              + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
              + "<title>Job Page</title>"
              + "</head>"
              + "<body>"
              + "User entered: </br>"
              + "<p>";

      String end = "</p>" + "</body>" + "</html>";

      out.write(begin);
      out.write(text);
      out.write(end);
      out.flush();
    } catch (IOException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    } finally {
      try {
        out.flush();
        if (out != null) out.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  @SuppressWarnings("unchecked")
  public void dumpCoverageAndConceptVectorAll(
      String fileEntityMI, String fileEntityEntropy, String fileEntityFreq, String fileCoverage) {
    BufferedWriter bwFileCoverage;

    HashMap<String, Double> entityMIMap = new GetEntityMI().getEntityMI(fileEntityMI);

    HashMap<String, Double> entityEntropyMap = new GetEntityMI().getEntityMI(fileEntityEntropy);

    HashMap<String, Double> entityFreqMap = new GetEntityFreq().getEntityFreq(fileEntityFreq);
    if (entityMIMap == null) {
      try {
        bwFileCoverage = new BufferedWriter(new FileWriter(fileCoverage));
        bwFileCoverage.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      return;
    }

    conceptCoverageMap = new HashMap<>();
    Vector<Integer> conceptList = new Vector<>();

    try {
      for (Integer id : ProbaseData.conceptEntitySetMap.keySet()) {
        double coverage =
            getConceptCoverage(
                ProbaseData.idTermMap.get(id), entityMIMap, entityEntropyMap, entityFreqMap);
        if (coverage != 0) {
          conceptCoverageMap.put(id, coverage);
          conceptList.add(id);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
    Collections.sort(conceptList, new cmp());
    try {
      bwFileCoverage = new BufferedWriter(new FileWriter(fileCoverage));

      for (Integer id : conceptList) {
        bwFileCoverage.write(
            String.valueOf(id)
                + "\t"
                + ProbaseData.idTermMap.get(id)
                + "\t"
                + String.valueOf(conceptCoverageMap.get(id)));
        bwFileCoverage.newLine();
        bwFileCoverage.flush();
      }
      bwFileCoverage.flush();
      bwFileCoverage.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private static void DoConvertDMS2D(String pointFile, String saveFile) {
    FileReader in = null;
    BufferedReader reader = null;
    int cntLine = 0;

    FileWriter out = null;
    BufferedWriter writer = null;
    try {
      out = new FileWriter(saveFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
    writer = new BufferedWriter(out);

    try {
      in = new FileReader(pointFile);
      reader = new BufferedReader(in);
      String str;
      Point3D pt3d = null;
      while (true) {
        str = reader.readLine();
        if (str == null) break;
        cntLine++;
        pt3d = Point3D.Create(str);
        if (cntLine % 1000000 == 0) {
          System.out.println("cnt : " + (cntLine));
          writer.flush();
        }

        if (pt3d != null) {
          writer.write(
              String.format("%.9f", pt3d.GetX())
                  + " "
                  + String.format("%.9f", pt3d.GetY())
                  + " "
                  + String.format("%.3f", pt3d.GetZ()));
          writer.newLine();

        } else {
          System.out.println("Err : " + str);
        }
      }
      System.out.println("Lines : " + cntLine);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
        writer.flush();
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #19
0
  public void msgHandler() {
    System.out.println("handling message");
    InputStream is = null;
    try {
      is = socket.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String query = br.readLine();
      if (query.equals("insert")) {
        String exe = br.readLine();
        System.out.println("query asked " + exe);
        String s = dbCon.insertQuery(exe);

        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(s + "\n");
        bw.flush();
        System.out.println("send " + s);

      } else if (query.equals("select")) {

        String exe = br.readLine();
        System.out.println("query asked " + exe);
        String returnQuery = dbCon.getResult(exe);
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(returnQuery);
        bw.flush();
        System.out.println("Message sent to the client is " + returnQuery);
      } else if (query.equals("update") || query.equals("delete")) {
        String exe = br.readLine();
        System.out.println("query asked " + exe);
        dbCon.insertQuery(exe);
      }
      System.out.println("Query received from client is " + query);

      // String returnQuery = dbCon.getResult(query);
      // OutputStream os = socket.getOutputStream();
      // OutputStreamWriter osw = new OutputStreamWriter(os);
      // BufferedWriter bw = new BufferedWriter(osw);
      // bw.write(returnQuery +"\n");
      // System.out.println("Message sent to the client is "+returnQuery);
      // bw.flush();

    } catch (IOException ex) {

    } finally {
      try {
        socket.close();
      } catch (Exception e) {
      }
    }
  }
Example #20
0
 public static void c(Set<Options> options) {
   File dir = null;
   if (virtex5) {
     dir = new File("/scratch/mul_pipe_virtex5/");
   } else {
     dir = new File("/scratch/mul_pipe_virtex2/");
   }
   dir.mkdirs();
   try {
     BufferedWriter topModule = new BufferedWriter(new FileWriter(new File(dir, "mul_pipe.v")));
     topModule.write(createModule(options));
     topModule.flush();
     topModule.close();
   } catch (IOException ex) {
     Logger.getLogger(MulPipeCreator.class.getName()).log(Level.SEVERE, null, ex);
   }
   // create not existing modules with coregen
   for (Options ops : options) {
     File f =
         new File(
             dir,
             String.format(
                 "mul_pipe_%s_%d_%d_%d.v", ops.signed ? "s" : "u", ops.WA, ops.WB, ops.WR));
     if (f.exists()) {
       System.out.println("skipping creation of " + ops + " because it already exists");
       continue;
     }
     try {
       String ls_str;
       File opts = File.createTempFile("foo", "bar");
       opts.deleteOnExit();
       BufferedWriter w = new BufferedWriter(new FileWriter(opts));
       if (virtex5) {
         w.write(createVirtex5(ops));
       } else w.write(create(ops));
       w.flush();
       Process ls_proc =
           Runtime.getRuntime().exec("coregen -b " + opts.getAbsolutePath(), null, dir);
       // get its output (your input) stream
       DataInputStream ls_in = new DataInputStream(ls_proc.getInputStream());
       try {
         while ((ls_str = ls_in.readLine()) != null) {
           System.out.println(ls_str);
         }
       } catch (IOException e) {
         System.exit(0);
       }
     } catch (IOException e1) {
       System.err.println(e1);
       System.exit(1);
     }
   }
 }
  private void prosesPermintaanClient(Socket koneksi) throws InterruptedException, IOException {
    String ip = koneksi.getInetAddress().getHostAddress();
    System.out.println("Dari: " + ip);
    InputStream masukan = koneksi.getInputStream();
    BufferedReader masukanReader = new BufferedReader(new InputStreamReader(masukan));
    String baris = masukanReader.readLine();
    String[] keluar = baris.split(" ");
    OutputStream keluaran = koneksi.getOutputStream();
    BufferedWriter keluaranBuf = new BufferedWriter(new OutputStreamWriter(keluaran));

    if (baris.equals(SIAPA)) {
      hasil = "" + ip;
      keluaran = koneksi.getOutputStream();
      keluaranBuf = new BufferedWriter(new OutputStreamWriter(keluaran));
      keluaranBuf.write(hasil);
      keluaranBuf.newLine();
      keluaranBuf.flush();
      System.out.println("hasil SIAPA " + ip);
      koneksi.close();

    } else if (baris.equals(WAKTU)) {
      hasil = "" + waktuStr;
      keluaran = koneksi.getOutputStream();
      keluaranBuf = new BufferedWriter(new OutputStreamWriter(keluaran));
      keluaranBuf.write(hasil);
      keluaranBuf.newLine();
      keluaranBuf.flush();
      System.out.println("hasil WAKTU " + waktuStr);
      koneksi.close();
    } else if (keluar[0].equals(WAKTU)) {
      int angka = Integer.parseInt(keluar[1]);
      Calendar kalender = Calendar.getInstance();
      kalender.add(Calendar.HOUR_OF_DAY, angka - 7); // WIB adalah GMT+7 sehingga -7 untuk waktu GMT
      String waktu = kalender.getTime().toString();
      keluaranBuf.write(waktu);
      keluaranBuf.newLine();
      keluaranBuf.flush();
      System.out.println("Waktu yang diubah  " + waktu);
      koneksi.close();
    } else {
      System.out.print(" Perintah client tidak dikenali ");
      hasil = "Perintah anda tidak dikenali";
      keluaran = koneksi.getOutputStream();
      keluaranBuf = new BufferedWriter(new OutputStreamWriter(keluaran));
      keluaranBuf.write(hasil);
      keluaranBuf.newLine();
      keluaranBuf.flush();
      koneksi.close();
    }
  }
  private void prosesPermintaanClient() throws InterruptedException, IOException {
    try {
      OutputStream keluaran = koneksi.getOutputStream();
      BufferedWriter keluaranBuf = new BufferedWriter(new OutputStreamWriter(keluaran));
      // IP address asal koneksi
      String ip = koneksi.getInetAddress().getHostAddress();
      // Tampilkan pesan
      System.out.println("Dari: " + ip);

      int i = 0;
      // dipastikan berulang 3x kecuali udah benar maka langsung break
      while (i != 3) {
        // Baca dari socket
        InputStream masukan = koneksi.getInputStream();
        BufferedReader masukanReader = new BufferedReader(new InputStreamReader(masukan));
        String baris = masukanReader.readLine();
        System.out.println("Tebak : " + baris);

        if (baris.charAt(0) == '3') {
          keluaranBuf.write("RIGHT");
          keluaranBuf.newLine();
          keluaranBuf.flush();
          break;
        } else {
          keluaranBuf.write("WRONG");
          keluaranBuf.newLine();
          keluaranBuf.flush();
        }
        i++;
      }

      // kalo udah 3 x coba tapi gagal terus masuk ke sini
      if (i == 3) {
        keluaranBuf.write("Sorry ! YOU LOSE ! GAME OVER\nangka = " + angka);
        keluaranBuf.newLine();
        keluaranBuf.flush();
      }

      /*
      // Tunggu 2 detik
      System.out.println("Tunggu...");
      Thread.sleep(2000);
      System.out.println("Selesai tunggu...");
      */
      koneksi.close();
    } catch (IOException err) {
      System.out.println(err);
    }
  }
  public static void main(String[] args) throws Exception {

    /*  BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
    */
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 2000);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 2000);
    String[] s = br.readLine().split(" ");
    int n = Integer.parseInt(s[0]);
    int q = Integer.parseInt(s[1]);
    int num[] = new int[n + 1];
    int[] m = new int[3 * n + 1]; // size = 2*n+1
    Arrays.fill(num, -1);
    s = br.readLine().split(" ");
    for (int i = 1; i <= n; i++) num[i] = Integer.parseInt(s[i - 1]);
    /// build tree
    maketree(1, 1, n, m, num);

    for (int qq = 1; qq <= q; qq++) {
      s = br.readLine().split(" ");
      int i = Integer.parseInt(s[0]);
      int j = Integer.parseInt(s[1]);
      int ans = query(1, 1, n, m, num, i, j);
      out.write("" + num[ans] + "\n");
      out.flush();
    }
  }
  void stopRecord() {
    recording = false;
    sendBroadcast(new Intent(C.actionSetIconRecord));
    try {
      mW.flush();
      mW.close();
      mW = null;

      // http://stackoverflow.com/questions/13737261/nexus-4-not-showing-files-via-mtp
      //			MediaScannerConnection.scanFile(this, new String[] { mFile.getAbsolutePath() }, null,
      // null);
      // http://stackoverflow.com/questions/5739140/mediascannerconnection-produces-android-app-serviceconnectionleaked
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).setData(Uri.fromFile(mFile)));

      Toast.makeText(
              this,
              new StringBuilder()
                  .append(getString(R.string.app_name))
                  .append("Record-")
                  .append(getDate())
                  .append(".csv ")
                  .append(getString(R.string.notify_toast_saved)),
              Toast.LENGTH_LONG)
          .show();
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(
              this,
              getString(R.string.notify_toast_error) + " " + e.getMessage(),
              Toast.LENGTH_LONG)
          .show();
    }
    topRow = true;
    mNM.notify(10, mNotificationRead);
  }
  public static void main(String[] args) throws MalformedURLException, IOException {
    String data = "";
    int i = 1000;
    // Collisions aus Textdatei lesen
    BufferedReader bw = new BufferedReader(new FileReader("Collisions.txt"));
    String line;
    while ((line = bw.readLine()) != null) {
      // TODO Stringbuilder verwenden
      // POST Daten erzeugen
      data +=
          URLEncoder.encode(line, "UTF-8")
              + "="
              + URLEncoder.encode(new Double(Math.random()).toString(), "UTF-8");
    }

    // Socket erzeugen
    String hostname = "test.com";
    int port = 80;
    InetAddress addr = InetAddress.getByName(hostname);
    Socket socket = new Socket(addr, port);
    while (i-- > 0) {
      // Header Senden
      String path = "/bla/index.php";
      BufferedWriter wr =
          new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
      wr.write("POST " + path + " HTTP/1.0\r\n");
      wr.write("Content-Length: " + data.length() + "\r\n");
      wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
      wr.write("\r\n");

      // Sende Daten
      wr.write(data);
      wr.flush();
    }
  }
Example #26
0
  public void saveToFile(String filename) throws IOException {
    FileOutputStream stream = new FileOutputStream(filename);

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));

    String nl = "\r\n";

    writer.write(numVertices + " " + numEdges + nl);

    for (int i = 0; i < numVertices; ++i) {
      Vertex vertex = vertices.get(i);
      writer.write(vertex.data.x + " " + vertex.data.y + nl);
    }

    if (numEdges > 0) {
      for (int i = 0; i < numVertices; ++i) {
        Vertex vertex = vertices.get(i);
        ArrayList<Vertex> adjList = vertex.adjacencyList;
        for (int j = 0; j < adjList.size(); ++j) {
          writer.write(adjList.get(j).id + " ");
        }
        writer.write(nl);
      }
    }

    writer.flush();
    writer.close();
    stream.close();
  }
Example #27
0
  // Starts redirection of streams.
  public void run() {
    BufferedReader r = new BufferedReader(new InputStreamReader(in), 1);
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out));
    byte[] buf = new byte[256];

    try {
      String line;

      /* This is to check that the distant vm has started,
       * if such a vm has been provided at construction :
       * - As soon as we can read something from r BufferedReader,
       *   that means the distant vm is already started.
       * Thus we signal associated JavaVM object that it is now started.
       */
      if (((line = r.readLine()) != null) && (javaVM != null)) {
        javaVM.setStarted();
      }

      // Redirects r on w.
      while (line != null) {
        w.write(preamble);
        w.write(line);
        w.newLine();
        w.flush();
        line = r.readLine();
      }

    } catch (IOException e) {
      System.err.println("*** IOException in StreamPipe.run:");
      e.printStackTrace();
    }
  }
Example #28
0
 /**
  * 把给定的字符串写到给定的文件中并使用给定的字符集编码
  *
  * @param file 给定的文件
  * @param string 给定的字符串
  * @param charset 给定的字符集
  * @param isAppend 是否追加到文件末尾
  * @throws IOException
  */
 public static void writeString(File file, String string, Charset charset, boolean isAppend)
     throws IOException {
   BufferedWriter bw = IOUtils.openBufferedWriter(file, charset, isAppend);
   bw.write(string);
   bw.flush();
   bw.close();
 }
Example #29
0
 /**
  * 把给定的字符数组写到给定的文件中并使用给定的字符集编码
  *
  * @param file 给定的文件中
  * @param chars 给定的字符数组
  * @param charset 给定的字符集
  * @param isAppend 是否追加到文件末尾
  * @throws IOException
  */
 public static void writeChar(File file, char[] chars, Charset charset, boolean isAppend)
     throws IOException {
   BufferedWriter bw = IOUtils.openBufferedWriter(file, charset, isAppend);
   IOUtils.write(bw, chars);
   bw.flush();
   bw.close();
 }
Example #30
0
 /**
  * 把给定的字符数组写到给定的文件中
  *
  * @param file 给定的文件中
  * @param chars 给定的字符数组
  * @param off 偏移量,从字符数组的此处开始获取数据写到文件中去
  * @param length 要写出的字符数
  * @param isAppend 是否追加到文件末尾
  * @throws IOException
  */
 public static void writeChar(File file, char[] chars, long off, int length, boolean isAppend)
     throws IOException {
   BufferedWriter bw = IOUtils.openBufferedWriter(file, isAppend);
   IOUtils.write(bw, chars, off, length);
   bw.flush();
   bw.close();
 }