Esempio n. 1
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();
  }
 private static String getConfigurationAsString(final String configArg) throws IOException {
   if (configArg.equalsIgnoreCase("-")) {
     return configArg;
   }
   StringBuilder stringBuilder = new StringBuilder();
   String line;
   String ls = System.getProperty("line.separator");
   if (configArg.startsWith("http")) {
     URL oracle = new URL(configArg);
     BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
     while ((line = in.readLine()) != null) {
       stringBuilder.append(line);
       stringBuilder.append(ls);
     }
     in.close();
   } else {
     File configFile = new File(configArg);
     BufferedReader reader = null;
     try {
       reader = new BufferedReader(new FileReader(configFile));
       while ((line = reader.readLine()) != null) {
         stringBuilder.append(line);
         stringBuilder.append(ls);
       }
     } finally {
       if (reader != null) reader.close();
     }
   }
   return stringBuilder.toString();
 }
Esempio n. 3
0
 /**
  * This assumes each line is of the form (number=value) and it adds each value in order of the
  * lines in the file
  *
  * @param file Which file to load
  * @return An index built out of the lines in the file
  */
 public static Index<String> loadFromFilename(String file) {
   Index<String> index = new HashIndex<String>();
   BufferedReader br = null;
   try {
     br = new BufferedReader(new FileReader(file));
     for (String line; (line = br.readLine()) != null; ) {
       int start = line.indexOf('=');
       if (start == -1 || start == line.length() - 1) {
         continue;
       }
       index.add(line.substring(start + 1));
     }
     br.close();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (br != null) {
       try {
         br.close();
       } catch (IOException ioe) {
         // forget it
       }
     }
   }
   return index;
 }
  public static void processPSOutput(Process psProcess, Processor<String> processor)
      throws IOException {
    @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
    BufferedReader stdOutput =
        new BufferedReader(new InputStreamReader(psProcess.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(psProcess.getErrorStream()));

    try {
      String s;
      stdOutput.readLine(); // ps output header
      while ((s = stdOutput.readLine()) != null) {
        processor.process(s);
      }

      StringBuilder errorStr = new StringBuilder();
      while ((s = stdError.readLine()) != null) {
        errorStr.append(s).append("\n");
      }
      if (errorStr.length() > 0) {
        throw new IllegalStateException("error:" + errorStr.toString());
      }
    } finally {
      stdOutput.close();
      stdError.close();
    }
  }
Esempio n. 5
0
  private static void exec(String command) {
    try {
      System.out.println("Invoking: " + command);
      Process p = Runtime.getRuntime().exec(command);

      // get standard output
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      // get error output
      input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      p.waitFor();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Esempio n. 6
0
  /** @param args the command line arguments */
  public static void main(String[] args) throws IOException {
    int recordwanted = 3;
    int numrecords = 3;
    boolean append = true;
    File data = new File("C:" + File.separatorChar + "temp" + File.separatorChar + "Lab1.txt");
    BufferedReader in = null;
    try {
      in = new BufferedReader(new FileReader(data));
      String line = in.readLine();
      while (line != null) {
        System.out.println(line);
        line = in.readLine(); // strips out any carriage return chars
      }

    } catch (IOException ioe) {
      System.out.println("Houston, we have a problem! couldn't read this file");
    } finally {
      try {
        in.close();
      } catch (Exception e) {

      }
    }
    System.out.println("----------------------------");
    //          PrintWriter out = new PrintWriter(
    //						new BufferedWriter(
    //						new FileWriter(data, append)));
    //          out.print("Darth Vador \nDeath Star \nSolar System, IL ???");
    //          out.close(); // be sure you close your streams when done!!
    //
    //	  System.out.println("Wrote file to: " + data.getAbsolutePath());
    in = null;
    List<String> Lines = new ArrayList<>();
    try {
      in =
          new BufferedReader(
              new FileReader("C:" + File.separatorChar + "temp" + File.separatorChar + "Lab1.txt"));
      String str;
      while ((str = in.readLine()) != null) {
        Lines.add(str);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (in != null) {
        in.close();
      }
    }
    System.out.print(Lines.get(recordwanted * numrecords - 3));
    System.out.print("'s state: ");
    String line = (Lines.get(recordwanted * numrecords - 1));
    String[] lines = line.split(" ");
    System.out.println(lines[1]);
  }
Esempio n. 7
0
 public boolean isEmpty() throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Verifying if playlist is empty or not.");
   BufferedReader br = new BufferedReader(new FileReader(new File(this.NAME)));
   if (br.readLine() != null) {
     br.close();
     return true;
   } else {
     br.close();
     return false;
   }
 }
  public static void main(String[] args) {
    File column = new File(args[0]);
    try {
      // how many different dbs are present
      LinkedHashMap dbs = new LinkedHashMap();
      BufferedReader in = new BufferedReader(new FileReader(column));
      String line;
      int index = 0;
      while ((line = in.readLine()) != null) {
        if (line.trim().length() == 0) continue;
        String[] tokens = line.split("\\|");
        for (int i = 0; i < tokens.length; i += 2) {
          if (dbs.containsKey(tokens[i]) == false) {
            dbs.put(tokens[i], new Integer(index++));
          }
        }
      }
      in.close();
      // print header
      Iterator it = dbs.keySet().iterator();
      while (it.hasNext()) {
        String c = (String) it.next();
        System.out.print("Reporter BioSequence DatabaseEntry [" + c + "]\t");
      }
      System.out.println();
      // print lines
      in = new BufferedReader(new FileReader(column));
      int numColumns = dbs.size();
      while ((line = in.readLine()) != null) {
        if (line.trim().length() == 0) {
          System.out.println();
        } else {
          String[] columns = new String[numColumns];
          String[] tokens = line.split("\\|");
          for (int i = 0; i < tokens.length; i += 2) {
            // System.out.println(line+"Tok"+tokens[i]);
            int columnIndex = ((Integer) dbs.get(tokens[i])).intValue();
            if (columns[columnIndex] == null) columns[columnIndex] = tokens[i + 1];
            else columns[columnIndex] = columns[columnIndex] + ";" + tokens[i + 1];
          }
          // print it
          for (int i = 0; i < numColumns; i++) {
            if (columns[i] == null) columns[i] = "";
          }
          System.out.println(Misc.stringArrayToString(columns, "\t"));
        }
      }
      in.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 9
0
  public GameFile() {
    game = "";

    // load character names and descriptions
    characters = "";
    File characterFile = new File("/home/cory/Programming/treasure_hunt/data/characters.data");
    try {
      BufferedReader in = new BufferedReader(new FileReader(characterFile));
      for (String s = in.readLine(); s != null; s = in.readLine()) {
        characters += s + "\n";
      }
      characters.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error! Couldn't load character data file.");
      System.exit(1);
    }

    // load weapon names and descriptions
    weapons = "";
    File weaponFile = new File("/home/cory/Programming/treasure_hunt/data/weapons.data");
    try {
      BufferedReader in = new BufferedReader(new FileReader(weaponFile));
      for (String s = in.readLine(); s != null; s = in.readLine()) {
        weapons += s + "\n";
      }
      weapons.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error! Couldn't load weapon data file.");
      System.exit(1);
    }

    // load treasure names and desciptions
    treasures = "";
    File treasureFile = new File("/home/cory/Programming/treasure_hunt/data/treasures.data");
    try {
      BufferedReader in = new BufferedReader(new FileReader(treasureFile));
      for (String s = in.readLine(); s != null; s = in.readLine()) {
        treasures += s + "\n";
      }
      treasures.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error! Couldn't load treasure data file.");
      System.exit(1);
    }
  }
Esempio n. 10
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    String line;
    StringTokenizer stk;
    while ((line = in.readLine()) != null) {
      stk = new StringTokenizer(line);
      int n = Integer.parseInt(stk.nextToken());
      int k = Integer.parseInt(stk.nextToken());
      int m = Integer.parseInt(stk.nextToken());

      long[][] dp = new long[n + 1][k + 1];

      dp[0][0] = 1;
      for (int i = 1; i <= n; ++i) // units
      for (int j = 1; j <= k; ++j) // bars
        for (int l = 1; l <= m && l <= i; ++l) // size of the next bar
          dp[i][j] += dp[i - l][j - 1];

      System.out.println(dp[n][k]);
    }

    in.close();
    System.exit(0);
  }
  private void parse(String filename) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
    StringBuffer sb = new StringBuffer();

    int j;
    while ((j = br.read()) != -1) {
      char next = (char) j;

      if (next >= 'A' && next <= 'z') {
        sb.append(next);
      }

      if (sb.length() == 4) {
        String qGram = sb.toString().toUpperCase();
        sb = new StringBuffer();

        int frequency = 0;

        if (map.containsKey(qGram)) {
          frequency = map.get(qGram);
        }

        frequency++;
        map.put(qGram, frequency);
      }
    }
    br.close();
  }
Esempio n. 12
0
  static void eliminarLugarFicheroLOC(Lugar lugar) {
    String fichero = lugar.getFicheroLOC();

    try {
      FileReader fr = new FileReader(fichero);
      BufferedReader br = new BufferedReader(fr);

      String linea;
      ArrayList lineas = new ArrayList();

      do {
        linea = br.readLine();
        if (linea != null) {
          if (!linea.substring(0, lugar.nombre.length()).equals(lugar.nombre)) lineas.add(linea);
        } else break;
      } while (true);
      br.close();
      fr.close();

      FileOutputStream fos = new FileOutputStream(fichero);
      PrintWriter pw = new PrintWriter(fos);

      for (int i = 0; i < lineas.size(); i++) pw.println((String) lineas.get(i));
      pw.flush();
      pw.close();
      fos.close();

    } catch (FileNotFoundException e) {
      System.err.println("error: eliminando " + e);

    } catch (IOException e) {
      System.err.println("error: eliminando 2 : " + e);
    }
  }
  public static ArrayList<TaggedWord> StopWordRemoval(ArrayList<TaggedWord> taggedWords) {
    ArrayList<TaggedWord> newList = new ArrayList<TaggedWord>();

    try {
      String path = "data/nltk_stoplist.txt";
      File textFile = new File(path);
      BufferedReader br = new BufferedReader(new FileReader(textFile));
      String stopwordsLine = br.readLine();
      br.close();

      String[] stopwords = stopwordsLine.split(",");
      HashMap<String, String> stopwordsDict = new HashMap<String, String>();
      for (int i = 0; i < stopwords.length; i++) {
        stopwordsDict.put(stopwords[i], stopwords[i]);
      }

      for (int i = 0; i < taggedWords.size(); i++) {
        String word = taggedWords.get(i).word();
        String posTag = taggedWords.get(i).tag();

        if (!stopwordsDict.containsKey(word.toLowerCase())) {
          String newWord, newPosTag;
          newWord = word;
          newPosTag = posTag;
          newList.add(new TaggedWord(newWord, newPosTag));
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return newList;
  }
Esempio n. 14
0
  public void processFile(String inputFileName) {

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFileName))));
      String[] headers = reader.readLine().split(SEPARATOR);

      for (String s : headers) {
        attrByValue.put(s, new HashSet<String>());
      }

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] columnValues = line.split(SEPARATOR);
        if (columnValues.length != headers.length) {
          System.err.println("There is a huge problem with data file");
        }

        for (int i = 0; i < columnValues.length; i++) {
          attrByValue.get(headers[i]).add(columnValues[i]);
        }
      }

      reader.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 15
0
  /**
   * @param fname String filename to read matrix from
   * @return Map of lists, 1 indexed representing the adjacency matrix
   */
  public Map<Integer, List<Integer>> readAdjacencyMatrix(String fname) {
    Map<Integer, List<Integer>> adjMatrix = new HashMap<>();
    int i = 1;

    try {
      BufferedReader br = new BufferedReader(new FileReader(fname));
      String line;
      while ((line = br.readLine()) != null) {
        List<String> words = Arrays.asList(line.split("\\s*"));
        List<Integer> wordVals = new ArrayList<>();
        for (String w : words) {
          if (w.equals("1") || w.equals("0")) {
            wordVals.add(Integer.parseInt(w));
          }
        }
        adjMatrix.put(i, wordVals);
        i += 1;
      }
      br.close();
      return adjMatrix;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
Esempio n. 16
0
  /**
   * Generate license plates from a file.
   *
   * @param filename
   */
  private void generateLicensePlates(String filename) {
    File licenseplatefile = getResourceFile(filename);
    BufferedReader in = null;
    try {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(licenseplatefile)));
    } catch (FileNotFoundException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<String> licensePlates = new ArrayList();
    String line;

    try {
      while ((line = in.readLine()) != null) {
        licensePlates.add(line);
      }
    } catch (IOException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        in.close();
      } catch (IOException ex) {
        Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    itLicensePlates = licensePlates.iterator();
  }
Esempio n. 17
0
 public void cutPlaylist() throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Cut Playlist.");
   String st;
   PrintWriter pw =
       new PrintWriter(new BufferedWriter(new FileWriter(new File(this.NAME + ".dec"))));
   BufferedReader br = new BufferedReader(new FileReader(new File(this.NAME)));
   if ((st = br.readLine()) != null) {
     String st2[];
     st = new File(st).toURL().toString();
     st2 = st.split("/");
     StringBuffer stb = new StringBuffer(st2[st2.length - 1]);
     StringBuffer stb2 = stb.reverse();
     String st3 = new String(stb2);
     int i = 0;
     while (st3.charAt(i) != '.') i++;
     String a = st3.substring(i + 1, st3.length());
     pw.print(new StringBuffer(a).reverse());
   }
   while ((st = br.readLine()) != null) {
     pw.println();
     String st2[];
     st = new File(st).toURL().toString();
     st2 = st.split("/");
     StringBuffer stb = new StringBuffer(st2[st2.length - 1]);
     StringBuffer stb2 = stb.reverse();
     String st3 = new String(stb2);
     int i = 0;
     while (st3.charAt(i) != '.') i++;
     String a = st3.substring(i + 1, st3.length());
     pw.print(new StringBuffer(a).reverse());
   }
   pw.close();
   br.close();
 }
Esempio n. 18
0
  public ConfigFile(String path) throws IOException {
    filePath = path;
    charset = Charset.forName("UTF-8");
    if (!new File(path).exists()) return;

    Collection<Line> currentLines = globalLines;
    InputStreamReader isr = new InputStreamReader(new FileInputStream(path), charset);
    BufferedReader br = new BufferedReader(isr);
    try {
      String l = br.readLine();
      while (l != null) {
        // 解决跨平台文本文件换行符不同的问题
        while (!l.isEmpty()
            && (l.charAt(l.length() - 1) == '\r' || l.charAt(l.length() - 1) == '\n'))
          l = l.substring(0, l.length() - 1);

        Sector sec = parseSectorName(l);
        if (sec != null) {
          currentLines = sec.lines;
          sectors.add(sec);
        } else {
          Line line = parseLine(l);
          currentLines.add(line);
        }

        l = br.readLine();
      }
    } finally {
      br.close();
      isr.close();
    }
  }
Esempio n. 19
0
  /** Reads the input data from the file and stores the data points in the vector */
  public void readData() throws IOException {

    BufferedReader in = new BufferedReader(new FileReader(this.inputFileName));
    String line = "";
    while ((line = in.readLine()) != null) {

      //			StringTokenizer st = new StringTokenizer(line, " \t\n\r\f,");
      String[] st = line.split(":");
      // 3维
      if (st.length == 3) {

        kMeansPoint dp =
            new kMeansPoint(
                Double.parseDouble(st[0]), Double.parseDouble(st[1]), Double.parseDouble(st[2]));
        dp.assignToCluster(0);
        this.kMeansPoints.add(dp);
      }

      if (st.length >= 2) {
        List<Double> listST = new ArrayList<Double>();
        for (String str : st) {
          listST.add(Double.parseDouble(str));
        }
        kMeansPoint dp = new kMeansPoint(listST);
        dp.assignToCluster(0);
        this.kMeansPoints.add(dp);
      }
    }

    in.close();
  } // end of readData()
Esempio n. 20
0
  // Read the file into a String
  public static String readFileToString(String filename) {
    try {
      File file = new File(filename);
      if (!file.exists()) {
        System.out.println("\nFILE DOES NOT EXIST: " + filename);
      }
      BufferedReader in = new BufferedReader(new FileReader(file));

      // Create an array of characters the size of the file
      char[] allChars = new char[(int) file.length()];

      // Read the characters into the allChars array
      in.read(allChars, 0, (int) file.length());
      in.close();

      // Convert to a string
      String allCharsString = new String(allChars);

      return allCharsString;

    } catch (FileNotFoundException e) {
      System.err.println(e);
      return "";
    } catch (IOException e) {
      System.err.println(e);
      return "";
    }
  }
Esempio n. 21
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
Esempio n. 22
0
 public static void addToPlaylist(File[] filesnames) throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Add to playlist (with parameters - filenames[]).");
   File f = new File(Lecteur.CURRENTPLAYLIST.NAME);
   File Fe =
       new File(
           Lecteur.CURRENTPLAYLIST.NAME.substring(0, Lecteur.CURRENTPLAYLIST.NAME.length() - 19)
               + "wssederdferdtdfdgetrdfdte.pl");
   PrintWriter br = new PrintWriter(new BufferedWriter(new FileWriter(Fe)));
   BufferedReader br1 = new BufferedReader(new FileReader(f));
   String st = null;
   while ((st = br1.readLine()) != null) {
     br.println(st);
   }
   for (int i = 0; i < filesnames.length - 1; i++) {
     br.println(filesnames[i].toString());
   }
   br.print(filesnames[filesnames.length - 1].toString());
   br.close();
   br1.close();
   new File(Lecteur.CURRENTPLAYLIST.NAME).delete();
   (new File(
           Lecteur.CURRENTPLAYLIST.NAME.substring(0, Lecteur.CURRENTPLAYLIST.NAME.length() - 19)
               + "wssederdferdtdfdgetrdfdte.pl"))
       .renameTo(new File(Lecteur.CURRENTPLAYLIST.NAME));
 }
Esempio n. 23
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    int cases = 1;
    while (true) {
      st = new StringTokenizer(in.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      if (n == 0 && m == 0) break;
      a = new int[n];
      b = new int[m];
      dp = new int[n + 1][m + 1];
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < n; i++) {
        a[i] = Integer.parseInt(st.nextToken());
        Arrays.fill(dp[i], -1);
      }
      Arrays.fill(dp[n], -1);
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken());

      System.out.println("Twin Towers #" + cases);
      System.out.println("Number of Tiles : " + LCS(0, 0));
      System.out.println();
      cases++;
    }
    in.close();
    System.exit(0);
  }
Esempio n. 24
0
    void close() {
      try {
        br.close();
      } catch (Exception e) {

      }
    }
Esempio n. 25
0
  static void writeNewData(String datafile) {

    try {
      BufferedReader bufr = new BufferedReader(new FileReader(datafile));
      BufferedWriter bufw = new BufferedWriter(new FileWriter(datafile + ".nzf"));

      String line;
      String[] tokens;

      while ((line = bufr.readLine()) != null) {

        tokens = line.split(" ");
        bufw.write(tokens[0]);
        for (int i = 1; i < tokens.length; i++) {

          Integer index = Integer.valueOf(tokens[i].split(":")[0]);
          if (nnzFeas.contains(index)) {
            bufw.write(" " + tokens[i]);
          }
        }
        bufw.newLine();
      }
      bufw.close();
      bufr.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
Esempio n. 26
0
 /**
  * read AIMLIF categories from a file into bot brain
  *
  * @param filename name of AIMLIF file
  * @return array list of categories read
  */
 public ArrayList<Category> readIFCategories(String filename) {
   ArrayList<Category> categories = new ArrayList<Category>();
   try {
     // Open the file that is the first
     // command line parameter
     FileInputStream fstream = new FileInputStream(filename);
     // Get the object
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
     String strLine;
     // Read File Line By Line
     while ((strLine = br.readLine()) != null) {
       try {
         Category c = Category.IFToCategory(strLine);
         categories.add(c);
       } catch (Exception ex) {
         System.out.println("Invalid AIMLIF in " + filename + " line " + strLine);
       }
     }
     // Close the input stream
     br.close();
   } catch (Exception e) { // Catch exception if any
     System.err.println("Error: " + e.getMessage());
   }
   return categories;
 }
Esempio n. 27
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = in.readLine()) != null) {
      int k = Integer.parseInt(line);
      List<Integer> xd = new ArrayList<Integer>();
      List<Integer> yd = new ArrayList<Integer>();

      for (int y = k + 1; y <= 2 * k; ++y) {
        if (k * y % (y - k) == 0) {
          int x = k * y / (y - k);
          xd.add(x);
          yd.add(y);
        }
      }

      sb.append(xd.size() + "\n");
      for (int i = 0; i < xd.size(); ++i)
        sb.append(String.format("1/%d = 1/%d + 1/%d\n", k, xd.get(i), yd.get(i)));
    }

    System.out.print(sb);

    in.close();
    System.exit(0);
  }
Esempio n. 28
0
  public String readFromFile(String fileName) {
    StringBuilder sb = new StringBuilder();
    try {
      if (exists(fileName) == false) { // todo - исправь это плиз, а то выебу DONE
        throw new FileNotFoundException();
      } else {

        File file = new File(String.valueOf(fileName));
        String s;

        try {
          BufferedReader bufferedReaderIn =
              new BufferedReader(new FileReader(file.getAbsoluteFile()));
          try {
            while ((s = bufferedReaderIn.readLine()) != null) {
              sb.append(s).append(" ");
            }
          } finally {
            bufferedReaderIn.close();
          }
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    } catch (FileNotFoundException e) {
      log.error("File not found");
    }

    return sb.toString();
  }
Esempio n. 29
0
  public void run() {
    System.out.println("New Communication Thread Started");

    try {
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String inputLine;
      String[] inputTemp = new String[3];

      while ((inputLine = in.readLine()) != null) {
        System.out.println("Server: " + inputLine);

        out.println(inputLine);

        if (inputLine.equals("Bye.")) break;
      }

      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
Esempio n. 30
0
  /**
   * ************************************************************************* loadHashFromFile -
   * loads a hastable from a file the format of the file is inflected_word base_form with a space
   * between both words ************************************************************************
   */
  private HashMap<String, ArrayList<String>> loadHashFromFile(String filename) {
    HashMap<String, ArrayList<String>> hashtable = new HashMap<String, ArrayList<String>>();

    try {
      BufferedReader br = new BufferedReader(new FileReader(filename));
      StringTokenizer st;

      for (; ; ) {

        String line = br.readLine();

        if (line == null) {
          br.close();
          break;
        } else {
          st = new StringTokenizer(line, " ");
          ArrayList<String> baseList = new ArrayList<String>();
          String inflected = st.nextToken();
          while (st.hasMoreTokens()) {
            baseList.add(st.nextToken());
          }
          hashtable.put(inflected, baseList);
        }
      }
    } catch (Exception e) {
      // System.out.println(line);
      System.out.println("Error:" + e);
    }

    return hashtable;
  }