예제 #1
1
  public static void main(String[] args) {
    System.out.println("Begin");
    Scanner scanner = new Scanner(System.in);
    String file1 = scanner.nextLine(), file2 = scanner.nextLine();

    BufferedReader reader;
    try {
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(file1))));
      while (reader.ready()) {
        allLines.add(reader.readLine());
      }
      reader.close();

      reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(file2))));
      while (reader.ready()) {
        forRemoveLines.add(reader.readLine());
      }
      reader.close();

      Solution solution = new Solution();
      solution.joinData();
    } catch (FileNotFoundException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
예제 #2
1
  public <P extends AbstractOfxProvider> BillingInfo getBillingInfo(Reader reader, P provider) {
    BillingInfo info = new BillingInfo();

    info.setCurrency("PLN");
    BufferedReader br = new BufferedReader(reader);
    try {
      if (br.ready()) {
        // skip header line
        String s = br.readLine();
        getSplit(s);
      }

      String line = "";
      while (br.ready() && line != null) {
        line = br.readLine();
        if (line != null && line.replace("\u0000", "").length() > 0) {
          createLine(line, info);
        }
      }
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    return info;
  }
예제 #3
1
  public static void execute(String[] args) {

    try {

      String hs2mmFile = args[0];
      HashMap human2mouse = human2mouse(hs2mmFile);
      String inputFile = args[1];
      String outputFile = args[2];
      FileWriter fwriter = new FileWriter(outputFile);
      BufferedWriter out = new BufferedWriter(fwriter);

      FileInputStream fstream = new FileInputStream(inputFile);
      DataInputStream din = new DataInputStream(fstream);
      BufferedReader in = new BufferedReader(new InputStreamReader(din));
      while (in.ready()) {
        String str = in.readLine();
        String[] split = str.split("\t");
        out.write(split[0] + "\t" + split[1]);
        for (int i = 2; i < split.length; i++) {
          if (human2mouse.containsKey(split[i])) {
            out.write("\t" + (String) human2mouse.get(split[i]));
          }
        }
        out.write("\n");
      }
      in.close();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testString() throws IOException {
    /** TODO: Test high-order characters */
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    String testString1 = "Ein groß Baum\nwith blossom";
    String testString2 = "Another string";
    targetPacket.write(testString1, false);
    targetPacket.write(testString2, false);
    targetPacket.xmit('R', new DataOutputStream(baos));

    byte[] ba = baos.toByteArray();
    assertEquals("Packet type character got mangled", 'R', (char) ba[0]);
    BufferedReader utfReader =
        new BufferedReader(
            new InputStreamReader(new ByteArrayInputStream(ba, 5, ba.length - 5), "UTF-8"));
    assertTrue("Packet did not provide a good character stream (1)", utfReader.ready());
    char[] ca = new char[100];
    int charsRead = utfReader.read(ca);
    assertEquals(
        "A test string got mangled (length mismatch)",
        (testString1 + testString2).length(),
        charsRead);
    assertEquals(
        "A test string got mangled", testString1 + testString2, new String(ca, 0, charsRead));
    assertFalse("Packet has extra stuff after character stream", utfReader.ready());
  }
예제 #5
0
 private void debugThrowable(Throwable problem) {
   if (problem != null) {
     if (problem instanceof Error) {
       debug("Error: ", problem.getMessage());
     } else {
       debug("Exception: ", problem.getMessage());
     }
     StringWriter stackTraceWriter = new StringWriter();
     problem.printStackTrace(new PrintWriter(stackTraceWriter));
     String trace = stackTraceWriter.toString();
     try {
       BufferedReader reader = new BufferedReader(new StringReader(trace));
       if (reader.ready()) {
         String traceLine = reader.readLine();
         int counter = 0;
         while (reader.ready() && traceLine != null && (counter < stackLength)) {
           debug(traceLine);
           traceLine = reader.readLine();
           counter++;
         }
       }
     } catch (Exception ioException) {
       error(
           "Serious error in LoggingTool while printing exception " + "stack trace: ",
           ioException.getMessage());
       logger.debug(ioException);
     }
     Throwable cause = problem.getCause();
     if (cause != null) {
       debug("Caused by: ");
       debugThrowable(cause);
     }
   }
 }
예제 #6
0
  /** Metodo que le os clientes de um ficheiro */
  public void lerLocalidades(String fileLocalidades, String fileLigacoes, int nrlocalidades)
      throws FileNotFoundException, IOException {
    BufferedReader readLoc = new BufferedReader(new FileReader(fileLocalidades));
    BufferedReader readLig = new BufferedReader(new FileReader(fileLigacoes));
    int nrligacoes;

    while (readLoc.ready() && nrlocalidades > 0) {

      String linhaLoc = readLoc.readLine();
      StringTokenizer stLoc = new StringTokenizer(linhaLoc, "|");
      nrligacoes = stLoc.countTokens() - 2;
      Localidade localidade = new Localidade(stLoc.nextToken(), stLoc.nextToken());

      while (nrligacoes > 0 && readLig.ready()) {
        String linhaLig = readLig.readLine();
        StringTokenizer stLig = new StringTokenizer(linhaLig, "|");
        stLig.nextToken();
        Ligacao lig =
            new Ligacao(
                stLig.nextToken(),
                Double.valueOf(stLig.nextToken()),
                Double.valueOf(stLig.nextToken()));
        localidade.addLigacao(lig);
        nrligacoes--;
      }
      this.addLocalidade(localidade);
      nrlocalidades--;
    }
    readLoc.close();
    readLig.close();
  }
  public List<JavaVersion> fetch() throws IOException, InterruptedException {
    List<JavaVersion> versions = new ArrayList<JavaVersion>();

    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("/usr/libexec/java_home -V");
    process.waitFor();
    InputStream inputStream = process.getErrorStream();
    InputStreamReader reader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(reader);
    try {
      if (bufferedReader.ready()) {
        // First Line with Title
        bufferedReader.readLine();
      }
      while (bufferedReader.ready()) {
        String versionString = bufferedReader.readLine();
        versionString = versionString.trim();
        String[] splitted = versionString.split("	");
        if (splitted.length == 3) {

          if (splitted[0].endsWith(":")) {
            splitted[0] = splitted[0].substring(0, splitted[0].length() - 1);
          }
          versions.add(new JavaVersion(splitted[0], splitted[1], splitted[2]));
        }
      }
    } finally {
      bufferedReader.close();
    }
    return versions;
  }
  public void openFile(String filename) {
    BufferedReader in = null;
    view.resetConsole();
    String programm_text = "";

    try {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
      view.setProgressBarText("Opening the file...");
    } catch (FileNotFoundException e1) {
      view.printError("File " + filename + " not found.", null);
    }
    try {
      while (in.ready()) {
        programm_text += in.readLine();
        if (in.ready()) {
          programm_text += "\n";
        }
      }
      in.close();
    } catch (IOException e) {
      view.printError("Caught IOException while reading " + filename, null);
    }

    view.resetProgressBar();
    view.setProgramText(programm_text);
  }
예제 #9
0
  public static void execute(String[] args) {

    try {

      HashMap map = new HashMap();
      HashMap map_peptide = new HashMap();
      String motifScoreFile = args[0];
      String raptor_dependent_inputFile = args[1];
      String raptor_dependent_ouputFile = args[2];

      FileInputStream fstream = new FileInputStream(motifScoreFile);
      DataInputStream din = new DataInputStream(fstream);
      BufferedReader in = new BufferedReader(new InputStreamReader(din));
      while (in.ready()) {
        String str = in.readLine();
        String[] split = str.split("\t");
        map.put(split[0], new Double(split[1]));
        map_peptide.put(split[0], split[2]);
      }
      in.close();

      FileWriter fwriter = new FileWriter(raptor_dependent_ouputFile);
      BufferedWriter out = new BufferedWriter(fwriter);

      fstream = new FileInputStream(raptor_dependent_inputFile);
      din = new DataInputStream(fstream);
      in = new BufferedReader(new InputStreamReader(din));

      while (in.ready()) {
        String str = in.readLine();
        String[] split = str.split("\t");
        if (split[1].split("\\|").length > 1) {
          String accession = split[1].split("\\|")[1];
          String site = split[3].replaceAll("S", "").replaceAll("T", "").replaceAll("Y", "");
          String[] split_sites = site.split("\\,");
          double max_score = Double.NEGATIVE_INFINITY;
          String sequence = "";
          for (String s : split_sites) {
            String key = accession + "_" + s;
            if (map.containsKey(key)) {
              sequence = (String) map_peptide.get(key);
              double score = (Double) map.get(key);
              if (max_score < score) {
                max_score = score;
              }
            }
          }

          out.write(accession + "_" + site + "\t" + max_score + "\t" + sequence + "\n");
        } else {
          // out.write(str + "\n");
        }
      }
      out.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #10
0
  @Test
  public void testGETThenNoContentFromTwoClients() throws Exception {
    InetSocketAddress proxyAddress =
        startProxy(
            startServer(
                new ServerSessionFrameListener.Adapter() {
                  @Override
                  public StreamFrameListener onSyn(Stream stream, SynInfo synInfo) {
                    Assert.assertTrue(synInfo.isClose());
                    Fields requestHeaders = synInfo.getHeaders();
                    Assert.assertNotNull(requestHeaders.get("via"));

                    Fields responseHeaders = new Fields();
                    responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                    responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                    ReplyInfo replyInfo = new ReplyInfo(responseHeaders, true);
                    stream.reply(replyInfo, new Callback.Adapter());
                    return null;
                  }
                }));

    Socket client1 = new Socket();
    client1.connect(proxyAddress);
    OutputStream output1 = client1.getOutputStream();

    String request =
        "" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + proxyAddress.getPort() + "\r\n" + "\r\n";
    output1.write(request.getBytes("UTF-8"));
    output1.flush();

    InputStream input1 = client1.getInputStream();
    BufferedReader reader1 = new BufferedReader(new InputStreamReader(input1, "UTF-8"));
    String line = reader1.readLine();
    Assert.assertTrue(line.contains(" 200"));
    while (line.length() > 0) line = reader1.readLine();
    Assert.assertFalse(reader1.ready());

    // Perform another request with another client
    Socket client2 = new Socket();
    client2.connect(proxyAddress);
    OutputStream output2 = client2.getOutputStream();

    output2.write(request.getBytes("UTF-8"));
    output2.flush();

    InputStream input2 = client2.getInputStream();
    BufferedReader reader2 = new BufferedReader(new InputStreamReader(input2, "UTF-8"));
    line = reader2.readLine();
    Assert.assertTrue(line.contains(" 200"));
    while (line.length() > 0) line = reader2.readLine();
    Assert.assertFalse(reader2.ready());

    client1.close();
    client2.close();
  }
예제 #11
0
  /**
   * Read the python preamble off of stderr. It ends when the prompy '>>> ' is detected.
   *
   * @return the preamble read from stderr
   */
  private String readPreamble(int timeoutMs) {
    String rv = null;
    StringBuilder sb = new StringBuilder();
    long timeout = System.currentTimeMillis() + timeoutMs;

    try {
      char[] prompt = {'>', '>', '>', ' '};
      int index = 0;

      while (true) {
        // sleep until there's input
        while (!stderr.ready()) {
          Thread.yield();

          if (timeoutMs >= 0 && System.currentTimeMillis() >= timeout)
            error("Timeout (" + timeoutMs + " ms) reached while reading python preamble.");
        }

        int readInt = stderr.read();

        if (readInt == -1) // end of stream
        error("End of output stream was reached while looking for python prompt.");

        char c = (char) readInt;

        sb.append(c);

        if (c == prompt[index]) {
          ++index;

          if (index == prompt.length) {
            // exit only if there are no more bytes to be read
            if (!stderr.ready()) break;
            else index = 0;
          }
        } else index = 0;
      }

      // trim off the prompt
      int len = sb.length();
      sb.delete(len - prompt.length, len);

      // remove \n and \r if they're at the end of the string
      trimSuffix(sb, '\n');
      trimSuffix(sb, '\r');

      rv = sb.toString();
    } catch (IOException e) {
      error("Error while reading python preamble.", e);
    }

    return rv;
  }
예제 #12
0
  @Test
  public void testGETThenSmallResponseContent() throws Exception {
    final byte[] data = "0123456789ABCDEF".getBytes("UTF-8");
    InetSocketAddress proxyAddress =
        startProxy(
            startServer(
                new ServerSessionFrameListener.Adapter() {
                  @Override
                  public StreamFrameListener onSyn(Stream stream, SynInfo synInfo) {
                    Assert.assertTrue(synInfo.isClose());
                    Fields requestHeaders = synInfo.getHeaders();
                    Assert.assertNotNull(requestHeaders.get("via"));

                    Fields responseHeaders = new Fields();
                    responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                    responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                    ReplyInfo replyInfo = new ReplyInfo(responseHeaders, false);
                    stream.reply(replyInfo, new Callback.Adapter());
                    stream.data(new BytesDataInfo(data, true), new Callback.Adapter());

                    return null;
                  }
                }));

    Socket client = new Socket();
    client.connect(proxyAddress);
    OutputStream output = client.getOutputStream();

    String request =
        "" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + proxyAddress.getPort() + "\r\n" + "\r\n";
    output.write(request.getBytes("UTF-8"));
    output.flush();

    InputStream input = client.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    String line = reader.readLine();
    Assert.assertTrue(line.contains(" 200 "));
    while (line.length() > 0) line = reader.readLine();
    for (byte datum : data) Assert.assertEquals(datum, reader.read());
    Assert.assertFalse(reader.ready());

    // Perform another request so that we are sure we reset the states of parsers and generators
    output.write(request.getBytes("UTF-8"));
    output.flush();

    line = reader.readLine();
    Assert.assertTrue(line.contains(" 200"));
    while (line.length() > 0) line = reader.readLine();
    for (byte datum : data) Assert.assertEquals(datum, reader.read());
    Assert.assertFalse(reader.ready());

    client.close();
  }
예제 #13
0
파일: Util.java 프로젝트: 2hanson/Superuser
  public static int getSuVersionCode() {
    Process process = null;
    String inLine = null;

    try {
      process = Runtime.getRuntime().exec("sh");
      DataOutputStream os = new DataOutputStream(process.getOutputStream());
      BufferedReader is =
          new BufferedReader(
              new InputStreamReader(new DataInputStream(process.getInputStream())), 64);
      os.writeBytes("su -v\n");

      // We have to hold up the thread to make sure that we're ready to read
      // the stream, using increments of 5ms makes it return as quick as
      // possible, and limiting to 1000ms makes sure that it doesn't hang for
      // too long if there's a problem.
      for (int i = 0; i < 400; i++) {
        if (is.ready()) {
          break;
        }
        try {
          Thread.sleep(5);
        } catch (InterruptedException e) {
          Log.w(TAG, "Sleep timer got interrupted...");
        }
      }
      if (is.ready()) {
        inLine = is.readLine();
        if (inLine != null && Integer.parseInt(inLine.substring(0, 1)) > 2) {
          inLine = null;
          os.writeBytes("su -V\n");
          inLine = is.readLine();
          if (inLine != null) {
            return Integer.parseInt(inLine);
          }
        } else {
          return 0;
        }
      } else {
        os.writeBytes("exit\n");
      }
    } catch (IOException e) {
      Log.e(TAG, "Problems reading current version.", e);
      return 0;
    } finally {
      if (process != null) {
        process.destroy();
      }
    }
    return 0;
  }
예제 #14
0
  public void insert(Connection conn, String file, String table) throws IOException, SQLException {
    PreparedStatement lockps = conn.prepareStatement("LOCK TABLES " + table + " WRITE");
    lockps.execute();
    lockps.close();

    String sql = "INSERT INTO " + table + " (tax_id, gene_id, accession) VALUES (?,?,?)";

    PreparedStatement ps = conn.prepareStatement(sql);

    FileInputStream fis = new FileInputStream(file);
    GZIPInputStream gis = new GZIPInputStream(fis);
    InputStreamReader ir = new InputStreamReader(gis);
    BufferedReader br = new BufferedReader(ir);

    int batchcount = 0;
    if (br.ready()) {
      br.readLine();
      while (br.ready()) {
        String line = br.readLine();
        Scanner sc = new Scanner(line);
        sc.useDelimiter("\t");

        int taxid = sc.nextInt();
        int geneid = sc.nextInt();
        sc.next();
        String accession = sc.next();
        if (accession.contains("_")) {
          batchcount++;
          accession = accession.substring(0, accession.indexOf("."));

          ps.setInt(1, taxid);
          ps.setInt(2, geneid);
          ps.setString(3, accession);
          sc.close();

          ps.addBatch();
          if (batchcount % 1000 == 0) {
            ps.executeBatch();
          }
        }
      }
      ps.executeBatch();
    }

    br.close();
    ir.close();
    gis.close();
    fis.close();

    ps.close();
  }
예제 #15
0
  public Pattern loadFile120_8(InputStream filePattern, InputStream fileOut) throws IOException {

    int x = 120;
    int d = 8;

    Pattern retorno = new Pattern();
    retorno.setX(new double[d][x]);
    retorno.setD(new double[d][d]);

    BufferedReader readerPattern = new BufferedReader(new InputStreamReader(filePattern));
    BufferedReader readerDesi = new BufferedReader(new InputStreamReader(fileOut));

    for (int i = 0; i < 5; i++) {
      readerPattern.readLine();
      readerDesi.readLine();
    }
    readerPattern.readLine();
    readerPattern.readLine();

    int i = 0;
    while (readerPattern.ready()) {
      String[] value = readerPattern.readLine().split("    ");
      int j = 0;
      for (String string : value) {
        if (string.trim().length() > 0) {
          retorno.getX()[j++][i] = new Double(string);
        }
      }
      i++;
    }

    i = 0;
    while (readerDesi.ready()) {
      String[] value = readerDesi.readLine().split("	");
      int j = 0;
      for (String string : value) {
        if (string.trim().length() > 0) {
          retorno.getD()[j++][i] = new Double(string);
        }
      }
      i++;
    }

    readerPattern.close();
    readerDesi.close();

    retorno.buildMatrix();

    return retorno;
  }
예제 #16
0
  public static void main(String[] args) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(args[0]));

      while (reader.ready()) {
        String s = reader.readLine();
        String[] a = s.split(" ");

        Date date =
            new GregorianCalendar(
                    Integer.parseInt(a[a.length - 1]),
                    Integer.parseInt(a[a.length - 2]) - 1,
                    Integer.parseInt(a[a.length - 3]))
                .getTime();

        String name = "";
        for (int i = 0; i <= a.length - 4; i++) name += a[i] + " ";

        name = name.substring(0, name.length() - 1);

        PEOPLE.add(new Person(name, date));
      }

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

    }
  }
예제 #17
0
  @Override
  public void run() {

    BufferedReader br = null;

    try {
      br = new BufferedReader(new FileReader(lista));
      String linha = null;
      while (br.ready()) {
        linha = br.readLine();

        if (sha1Password(linha).equalsIgnoreCase(getRecebe())) {
          System.out.println("Senha é : " + linha);
          System.exit(0);
        }
      }
    } catch (FileNotFoundException ex) {
      Logger.getLogger(DicionarioSha1.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(0);
    } catch (IOException ex) {
      Logger.getLogger(DicionarioSha1.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(0);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(DicionarioSha2.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(0);
    } finally {
      try {
        br.close();
      } catch (IOException ex) {
        Logger.getLogger(DicionarioSha1.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
예제 #18
0
  public static void execute(String[] args) {

    try {
      String inputFile = args[0];
      String gtfFile = args[1];
      String outputFile = args[2];
      GTFFile gtf = new GTFFile();
      gtf.initialize(gtfFile);

      FileWriter fwriter = new FileWriter(outputFile);
      BufferedWriter out = new BufferedWriter(fwriter);

      FileInputStream fstream = new FileInputStream(inputFile);
      DataInputStream din = new DataInputStream(fstream);
      BufferedReader in = new BufferedReader(new InputStreamReader(din));
      String header = in.readLine();
      out.write(header + "\n");
      while (in.ready()) {
        String str = in.readLine();
        String[] split = str.split("\t");
        String geneName = (String) gtf.geneid2geneName.get(split[0].replaceAll("\"", ""));
        // System.out.println(str + "\t" + geneName);
        out.write(geneName + "");
        for (int i = 1; i < split.length; i++) {
          out.write("\t" + split[i]);
        }
        out.write("\n");
      }
      in.close();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #19
0
 private static String processFileReader(String fileName) {
   StringBuilder builder = new StringBuilder();
   try {
     outLog.println(fileName + " to be read");
     outLog.flush();
     FileReader fileReader = new FileReader(fileName);
     BufferedReader bufferedReader = new BufferedReader(fileReader);
     try {
       while (bufferedReader.ready()) {
         String line = bufferedReader.readLine();
         builder.append(line);
         builder.append('\n');
       }
       bufferedReader.close();
     } catch (NullPointerException e2) {
     }
   } catch (FileNotFoundException e) {
     outLog.println("PreProcess FileNotFoundException");
     outLog.flush();
   } catch (IOException e) {
     outLog.println("PreProcess IOException");
     outLog.flush();
   }
   return builder.toString();
 }
예제 #20
0
  /** {@inheritDoc} */
  public String RPC(String Name, String Method, String[] Args) {
    // write to serial port and receive result
    String Response;
    String Arguments = "";
    if (Args != null) {
      int s = Args.length;
      for (int i = 0; i < s; i++) {
        Arguments = Arguments + " " + Args[i];
      }
    }
    try {
      to_mbed.println("/" + Name + "/" + Method + Arguments);
      mbedSerialPort.notifyOnDataAvailable(false);
    } catch (NullPointerException e) {

    }
    boolean valid = true;
    try {
      while (reader.ready() == false) {}
      ;
      do {
        Response = reader.readLine();

        if (Response.length() >= 1) {
          valid = Response.charAt(0) != '!';
        }
      } while (valid == false);
    } catch (IOException e) {
      System.err.println("IOException, error reading from port");
      Response = "error";
    }

    mbedSerialPort.notifyOnDataAvailable(true);
    return (Response);
  }
  public void leDados(String filePath) throws FileNotFoundException, IOException {
    List<StringBuilder> listaGeracoes = new ArrayList<>();
    String linhaLida;
    int numGeracao = -1;
    int contadorRepeticao = 0;

    try (FileReader fr = new FileReader(filePath);
        BufferedReader br = new BufferedReader(fr)) {
      while (br.ready()) {
        if (numGeracao == 499) {
          contadorRepeticao++;
          if (contadorRepeticao % 10 == 0) {
            imprime(contadorRepeticao, listaGeracoes);
            listaGeracoes = new ArrayList<>();
          }
          numGeracao = -1;
        }
        linhaLida = br.readLine();
        if (linhaLida.contains("Geracao")) {
          numGeracao++;
          atualizaListaGeracoes(listaGeracoes, numGeracao, br);
        }
      }
      br.close();
      fr.close();
    }
  }
예제 #22
0
  public String LerLog() {
    String Path = "Log.txt";
    FileReader fr = null;
    BufferedReader br = null;
    try {
      fr = new FileReader(Path);
      br = new BufferedReader(fr);
      StringBuilder sb = new StringBuilder();
      while (br.ready()) {
        sb.append(br.readLine());
        sb.append("\n");
      }

      return sb.toString();
    } catch (IOException ex) {
      // JOptionPane.showMessageDialog(null, "Erro ao abrir o arquivo" + ex.getMessage());
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException ex) {
          // JOptionPane.showMessageDialog(null, "Erro ao abrir o arquivo" + ex.getMessage());
        }
      }
      if (fr != null) {
        try {
          fr.close();
        } catch (IOException ex) {
          // JOptionPane.showMessageDialog(null, "Erro ao abrir o arquivo" + ex.getMessage());
        }
      }
    }
    return null;
  }
예제 #23
0
 public void load(InputStream inputStream) throws Exception {
   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   ArrayList<String> us = new ArrayList<>();
   while (bufferedReader.ready()) {
     us.add(bufferedReader.readLine());
   }
   for (int i = 0; i < us.size(); i += 5) {
     User user = new User();
     user.setFirstName(us.get(i));
     user.setLastName(us.get(i + 1));
     user.setBirthDate(new Date(Long.parseLong(us.get(i + 2))));
     user.setMale(Boolean.valueOf(us.get(i + 3)));
     String country = us.get(i + 4);
     User.Country country1 = null;
     if (country.equals("UKRAINE")) {
       country1 = User.Country.UKRAINE;
     } else if (country.equals("RUSSIA")) {
       country1 = User.Country.RUSSIA;
     } else if (country.equals("OTHER")) {
       country1 = User.Country.OTHER;
     }
     user.setCountry(country1);
     users.add(user);
   }
   bufferedReader.close();
 }
예제 #24
0
 private int readCharNonBlocking(BufferedReader reader) throws IOException {
   if (reader.ready()) {
     return reader.read();
   } else {
     return -1;
   }
 }
예제 #25
0
파일: Main.java 프로젝트: DaciCop/dacicop
  public void proccessConnection() {
    iptables = new AccesIptables();
    // Thread thread = new Thread(iptables);
    // thread.start();
    try {
      while (in.ready()) {

        String linie[] = in.readLine().split("\\¶{1}");
        // System.out.println("Linie mesaj" +"- "+ linie[0] +" - "+ linie[1] +" - "+
        // java.lang.Boolean.parseBoolean(linie[2]));
        iptables.accesIptables(linie[0], linie[1], java.lang.Boolean.parseBoolean(linie[2]));
        // if (sesUtilDeDezactivat!=null) if (sesUtilDeDezactivat.compareTo("")!=0)
        // {interziceListaCereri(sesUtilDeDezactivat);
        // String idutil=dbcon.getString("SELECT id from utilizatori where
        // utilizator='"+sesUtilDeDezactivat+"'", "id");
        // String ip = dbcon.getString("SELECT ip from sesiuni where idutil='"+idutil+"' and
        // datapornire=dataoprire order by datapornire desc", "ip");
        // dbcon.update("UPDATE sesiuni set dataoprire=NOW() where ip='"+ip+"' and
        // datapornire=dataoprire");
      }
      out.flush();
      out.close();
    } catch (Exception ex) {
      //  jurnal.println("Eroare la procesarea conexiunii: "+ex.getMessage());
      ex.printStackTrace();
    }
    iptables.run();
  }
예제 #26
0
 // ------------------------------------------------------------
 private int getExpectedServers(ServerDescription[] validServers) throws GenericException {
   int expectedServers = 0;
   try {
     BufferedReader br = new BufferedReader(new FileReader(rb.getString("NewSubagentsFile")));
     String theLine;
     while (br.ready()) {
       theLine = br.readLine();
       if (theLine.split(",").length != 3) continue;
       String[] splitVals = theLine.split(",");
       System.out.println(
           "IP: " + splitVals[0] + " Port: " + splitVals[1] + " server number: " + splitVals[2]);
       // mylog.write("IP: " + splitVals[0] + " Port: " + splitVals[1] +
       // " server number: " + splitVals[2] +"\n", true);
       try {
         validServers[expectedServers].setIP(splitVals[0]);
         validServers[expectedServers].port = Integer.valueOf(splitVals[1]);
         validServers[expectedServers].serverNumber = Integer.valueOf(splitVals[2]);
         expectedServers++;
       } catch (GenericException e) {
         br.close();
         throw new GenericException("");
       }
     } // End while(br.read());
     br.close();
   } catch (IOException e) {
     throw new GenericException("");
   }
   // mylog.write("returning " + expectedServers +"\n", true);
   return (expectedServers);
 }
예제 #27
0
  /*! This method runs all the time and listens to data from the SK6 and posts the data through
  	events to the event heap
  */
  public void run() {
    String data;
    String[] tokens;
    Integer value;
    Event e;

    System.out.println("Bluetooth thread, waiting for data");
    while (running == true) {
      try {
        if (inBufReader.ready()) {
          data = inBufReader.readLine();
          tokens = data.split(",");
          e = new Event("Shake");
          e.addField("ProxyID", proxyID);
          e.setPostValue("TimeToLive", new Integer(50)); // set time to live to 50 msec
          e.setPostValue("Sensor", tokens[0]);
          for (int i = 1; i < tokens.length; i++) {
            if (tokens[i].startsWith("+")) { // eliminate Number format exception
              value = new Integer(tokens[i].substring(1));
            } else {
              value = new Integer(tokens[i]);
            }
            e.setPostValue("Data" + i, value);
          }
          eventHeap.putEvent(e);
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    System.out.println("out of run");
  }
  private void executeCommand(Socket client) {
    try {
      try {
        client.setSoTimeout(30000);
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintStream out = new PrintStream(client.getOutputStream());
        System.out.println("I/O setup done");

        String line = in.readLine();
        while (in.ready() && line != null) {

          System.out.println(line);
          line = in.readLine();
        }
        System.out.println(line);

        File file = new File("index.html");
        System.out.println(file.getName() + " requested.");
        sendFile(out, file);

        out.flush();
        out.close();
        in.close();
      } finally {
        client.close();
        System.out.println("A connection is closed.");
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }
예제 #29
0
 public void getWords(String fileName) throws IOException {
   this.word = new ArrayList<String>();
   BufferedReader buf = new BufferedReader(new FileReader(fileName));
   while (buf.ready()) {
     this.word.add(buf.readLine());
   }
 }
예제 #30
0
  /* das Lesen aus der Datei erfolgt Zeilenweise */
  private static void aus_datei_lesen(File datei) throws IOException, FileNotFoundException {
    // fehler_ausgeben("STATUS;Datei lesen? "+datei.canRead()+";");
    String zeile_aus_datei = "";

    try {
      FileReader zeichen_leser = new FileReader(datei);
      BufferedReader zeilen_leser = new BufferedReader(zeichen_leser);
      while (zeilen_leser.ready()) {
        zeile_aus_datei = zeilen_leser.readLine();
        String[] film_als_array = new String[23];
        film_als_array = zeile_aus_datei.split(";");
        Film film_pro_zeile = new Film(film_als_array);
      }
      zeilen_leser.close();
      zeichen_leser.close();
    } catch (FileNotFoundException file_e) {
      FileNotFoundException ex_keine_datei;
      ex_keine_datei =
          new FileNotFoundException(
              "FEHLER;Datei \"" + datei.getName() + "\" ist nicht vorhanden.;");
      throw ex_keine_datei;
    } catch (IOException io_e) {
      IOException ex_lesefehler;
      ex_lesefehler =
          new IOException(
              "FEHLER;Beim Lesen aus der Datei \""
                  + datei.getName()
                  + "\" trat ein Fehler auf.\n Daten können unvollständige sein.;");
      throw ex_lesefehler;
    }
  }