Example #1
2
  @Test
  public void kmeans_test() throws IOException {
    File file = new File(filename);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line;
    List<Vector<Double>> vectors = new ArrayList<Vector<Double>>();
    List<Integer> oc = new ArrayList<Integer>();
    while ((line = br.readLine()) != null) {
      String[] values = line.split(separator);
      Vector<Double> vector = new Vector<Double>(values.length - 1);
      for (int i = 0; i < values.length - 1; i++) {
        vector.add(i, Double.valueOf(values[i]));
      }
      vectors.add(vector);

      String clazz = values[values.length - 1];
      if (clazz.equals("Iris-setosa")) {
        oc.add(0);
      } else if (clazz.equals("Iris-versicolor")) {
        oc.add(1);
      } else {
        oc.add(2);
      }
    }
    br.close();
    fr.close();
    Matrix matrix = new Matrix(vectors);
    KMeansClustering kmeans = new KMeansClustering();
    int[] clusters = kmeans.cluster(matrix, 3);
    int[][] classMatrix = new int[3][3];
    for (int i = 0; i < oc.size(); i++) {
      classMatrix[oc.get(i)][clusters[i]]++;
    }
    System.out.println("	   setosa versicolor virginica");
    System.out.println(
        "setosa       "
            + classMatrix[0][0]
            + "       "
            + classMatrix[0][1]
            + " 	"
            + classMatrix[0][2]);
    System.out.println(
        "versicolor    "
            + classMatrix[1][0]
            + "       "
            + classMatrix[1][1]
            + " 	"
            + classMatrix[1][2]);
    System.out.println(
        "virginica     "
            + classMatrix[2][0]
            + "       "
            + classMatrix[2][1]
            + " 	"
            + classMatrix[2][2]);

    System.out.println(
        "Rand index: " + new RandIndex().calculate(oc.toArray(new Integer[oc.size()]), clusters));
  }
Example #2
1
 private static void init() throws IOException {
   startComponentMethods = new HashMap<String, Set<String>>();
   subSignatures = new HashSet<String>();
   FileReader fr = null;
   BufferedReader br = null;
   String line = null;
   try {
     fr = new FileReader(IPC_FILE);
     br = new BufferedReader(fr);
     while ((line = br.readLine()) != null) {
       String[] tokens = line.split(":");
       String className = tokens[0].substring(1);
       String subSignature = tokens[1].substring(1, tokens[1].length() - 1);
       Set<String> methods = startComponentMethods.get(className);
       if (methods == null) {
         methods = new HashSet<String>();
         methods.add(subSignature);
         subSignatures.add(subSignature);
         startComponentMethods.put(className, methods);
       } else {
         methods.add(subSignature);
         subSignatures.add(subSignature);
       }
     }
   } catch (IOException ioe) {
     System.out.print(ioe.toString());
   } finally {
     if (br != null) br.close();
     if (fr != null) fr.close();
   }
 }
Example #3
0
  private static void getIPS() throws IOException {
    String result = "";
    String filePath = "F:\\Proxys\\";
    char[] str = new char[100000];

    // 匹配 xxx.xxx.xxx.xxx yyyy的正则表达式

    Pattern pattern = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d+\\s\\d+");

    for (int i = 1; i <= 34; ++i) {
      String fileName = "proxy" + Integer.toString(i) + ".txt";
      File file = new File(filePath, fileName);
      FileReader fr = new FileReader(file);
      int j = 0;
      String tempStr;
      while (fr.read(str) != -1) {
        // System.out.println("ttt");
        //	System.out.println(str);
      }
      tempStr = String.valueOf(str);
      Matcher matcher = pattern.matcher(tempStr);
      int step = 0;
      while (matcher.find(step)) {
        result += matcher.group() + "\r\n";
        step = matcher.end();
      }
    }
    writeFile(filePath, "ProxyIp.txt", result);
  }
Example #4
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;
  }
Example #5
0
  /**
   * create new a agent service configuration from the file conf.cnf
   *
   * @throws AgentServiceException
   */
  private static void getConf() throws AgentServiceException {
    // read the json string that contain the properties from the file
    File confFile = new File("conf.cnf");
    FileReader fr;

    try {
      fr = new FileReader(confFile);
    } catch (FileNotFoundException e) {
      throw new AgentServiceException("cound not file the configuration file - conf.cnf", e);
    }

    char[] buffer = new char[(int) confFile.length()];

    try {
      fr.read(buffer);
    } catch (IOException e) {
      throw new AgentServiceException("problem to read from the configuration file", e);
    } finally {
      try {
        fr.close();
      } catch (IOException e) {
      }
    }

    String jsonConfStr = new String(buffer);

    // and use the json conf contractor
    conf = AgentServiceConf.IntallConf(jsonConfStr);
  }
Example #6
0
 public static Map<String, String> readFile2Map(String path, String regular) throws IOException {
   if (StringUtils.isBlank(regular)) {
     return null;
   }
   if (StringUtils.isBlank(path)) {
     return null;
   }
   Map<String, String> map = new HashMap<String, String>();
   File file = new File(path);
   FileReader fReader = new FileReader(file);
   BufferedReader bReader = new BufferedReader(fReader);
   String temp = null;
   String[] tempArr = (String[]) null;
   while ((temp = bReader.readLine()) != null) {
     if (StringUtils.isNotBlank(temp)) {
       tempArr = temp.split(regular);
       if (tempArr.length > 1) {
         String username = tempArr[0];
         String password = tempArr[1];
         if ((StringUtils.isNotBlank(username)) && (StringUtils.isNotBlank(password))) {
           map.put(username.trim(), password.trim());
         }
       }
     }
     temp = null;
     tempArr = (String[]) null;
   }
   bReader.close();
   fReader.close();
   file = null;
   return map;
 }
Example #7
0
  public static void readAndWrite(File fIn, File fOut) {
    FileReader fileReader = null;
    FileWriter fileWriter = null;

    try {
      fileReader = new FileReader(fIn);
      fileWriter = new FileWriter(fOut);
      char[] temp = new char[1024];
      while ((fileReader.read(temp)) != -1) {
        fileWriter.write(temp);
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (fileReader != null)
        try {
          fileReader.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      if (fileWriter != null) {
        try {
          fileWriter.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
Example #8
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;
    }
  }
Example #9
0
  public static String fileToString(final File src, final int readBufferSize)
      throws FileNotFoundException, IOException {
    final FileReader in = new FileReader(src);

    final long length = src.length();
    if (length > 1024 * 1024 * 1024) {
      throw new IllegalArgumentException();
    }

    final char[] readBuffer = new char[readBufferSize];

    final StringBuilder result = new StringBuilder((int) length);
    try {
      while (true) {
        final int numRead = in.read(readBuffer, 0, readBufferSize);
        if (numRead < 0) {
          break;
        }

        result.append(readBuffer, 0, numRead);
      }
    } finally {
      in.close();
    }

    return (result.toString());
  }
 public static void myReadPropertiesMethod(String filePath) {
   FileReader fr = null;
   BufferedReader br = null;
   Properties ppt = new Properties();
   try {
     fr = new FileReader(filePath);
     br = new BufferedReader(fr);
     String line = null;
     while ((line = br.readLine()) != null) {
       String[] keyAndValue = line.split("=");
       ppt.setProperty(keyAndValue[0], keyAndValue[1]);
     }
     System.out.println("直接打印:");
     System.out.println(ppt.toString() + "\n");
     System.out.println("list()方法:");
     ppt.list(System.out);
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       br.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
     try {
       fr.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  public S3UrlListDA() {
    File file = new File("/usr/share/jetty/webapps/credentials");
    String accessKey = null;
    String secretKey = null;
    try {
      String line;
      FileReader reader = new FileReader(file);
      BufferedReader in = new BufferedReader(reader);
      while ((line = in.readLine()) != null) {
        if (line.contains("AWSAccessKeyId")) {
          accessKey = line.split("=")[1].trim();
        } else if (line.contains("AWSSecretKey")) {
          secretKey = line.split("=")[1].trim();
        }
      }
      in.close();
      reader.close();
    } catch (FileNotFoundException e) {
      System.out.println("S3UrlListDA : reading from local credential file failed");
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("S3UrlListDA : reading from local credential file failed");
      e.printStackTrace();
    }

    this.bucketName = "edu.upenn.cis455.project.urls";
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
    this.s3client = new AmazonS3Client(awsCreds);
  }
Example #12
0
  public void open() throws IOException {

    paneCenter.getChildren().clear();

    String station = (String) cbStations.getValue();

    File f = new File("database\\" + station + "\\status.txt");
    FileReader fr1 = new FileReader(f);
    LineNumberReader ln = new LineNumberReader(fr1);
    int count = 0;
    while (ln.readLine() != null) {
      count++;
    }
    ln.close();
    fr1.close();

    FileReader fr2 = new FileReader(f);
    BufferedReader br = new BufferedReader(fr2);

    paneCenter.add(new Label("Last seen : " + (br.readLine())), 0, 0);

    for (int i = 1; i < count; i++) {
      paneCenter.add(new Label(br.readLine()), 0, i);
    }
    br.close();
    fr2.close();

    addQuantityToCB();
  }
  private static List<SchloettQueryFormat> parseQueryiesFile(
      List<File> files, SchloettQueryExtraction extraction)
      throws JsonSyntaxException, IOException {
    FileReader freader;
    List<SchloettQueryFormat> queries = new ArrayList<SchloettQueryFormat>();

    for (File file : files) {
      try {
        freader = new FileReader(file);
        BufferedReader br = new BufferedReader(freader);

        ObjectMapper mapper = new ObjectMapper();
        HashMap format = mapper.readValue(file, new HashMap<String, SchloettQuery>().getClass());

        queries.add(new SchloettQueryFormat(format));
        br.close();
        freader.close();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return queries;
  }
  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();
    }
  }
Example #15
0
  public static String getCpu() {
    String var0 = null;
    FileReader var1 = null;
    BufferedReader var2 = null;

    try {
      var1 = new FileReader("/proc/cpuinfo");
      if (var1 != null) {
        try {
          var2 = new BufferedReader(var1, 1024);
          var0 = var2.readLine();
          var2.close();
          var1.close();
        } catch (IOException var4) {
          YLog.e(TAG, "Could not read from file /proc/cpuinfo--->" + var4);
        }
      }
    } catch (FileNotFoundException var5) {
      YLog.e(TAG, "Could not open file /proc/cpuinfo--->" + var5);
    }

    if (var0 != null) {
      int var3 = var0.indexOf(58) + 1;
      var0 = var0.substring(var3);
    }

    return var0.trim();
  }
  /**
   * Get the License
   *
   * @param license file name
   * @return license text
   */
  public static String getLicenseText(String licenseFile) {
    // Load in default license

    FileReader fr = null;
    BufferedReader br = null;
    try {
      fr = new FileReader(licenseFile);
      br = new BufferedReader(fr);
      String lineIn;
      license = "";
      while ((lineIn = br.readLine()) != null) {
        license = license + lineIn + '\n';
      }
    } catch (IOException e) {
      fatal("Can't load configuration", e);

      // FIXME: Maybe something more graceful here, but with the
      // configuration we can't do anything
      System.exit(1);
    } finally {
      if (br != null)
        try {
          br.close();
        } catch (IOException ioe) {
        }

      if (fr != null)
        try {
          fr.close();
        } catch (IOException ioe) {
        }
    }

    return license;
  }
  public static void main(String[] args) {
    try {

      // 非常便捷地操作纯文本数据,若想要写出原始的字节流,推荐使用FileInputStream
      FileReader fr = new FileReader("test.txt");
      BufferedReader br = new BufferedReader(fr);

      FileWriter fw = new FileWriter("new_text.txt");
      BufferedWriter bw = new BufferedWriter(fw);

      String line;
      while ((line = br.readLine()) != null) {
        bw.write(line + "\n");
      }
      bw.flush();

      bw.close();
      fw.close();
      br.close();
      fr.close();
      System.out.println("done");

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public static <T> T run(SubDirectory dir, String fileName, Map context) {
   fileName = dir + File.separator + fileName;
   String fileNameWExt = fileName + ".groovy";
   if (!new File(fileName).exists() && new File(fileNameWExt).exists()) {
     fileName = fileNameWExt;
   }
   FileReader fileReader = null;
   try {
     fileReader = new FileReader(fileName);
     Bindings bindings = new SimpleBindings(context);
     SimpleScriptContext scriptContext = new SimpleScriptContext();
     scriptContext.setBindings(bindings, SimpleScriptContext.ENGINE_SCOPE);
     T ret = (T) getGroovyEngine().eval(fileReader, scriptContext);
     return ret;
   } catch (Exception e) {
     LOG.debug(e, e);
     throw new RuntimeException("Executing the requested script failed: " + fileName, e);
   } finally {
     if (fileReader != null) {
       try {
         fileReader.close();
       } catch (IOException e) {
         LOG.error(e);
       }
     }
   }
 }
Example #19
0
  /** 返回f对应的arff文件对应的Arff对象。 */
  public static Arff parse(File f) {
    if (f == null) {
      return null;
    }

    BufferedReader br = null;
    FileReader fr = null;

    arff = new Arff();
    String tmp;
    stage = 1;

    try {
      fr = new FileReader(f);
      br = new BufferedReader(fr);
      tmp = br.readLine();
      while (tmp != null) {
        // System.out.printf("%s\n", tmp);
        parserLine(tmp);
        tmp = br.readLine();
      }

    } catch (IOException e) {
      System.out.printf("IO ERROR!! In ARFFParser.");
      return null;
    } finally {
      try {
        fr.close();
        br.close();
      } catch (IOException e1) {
      }
    }

    return arff;
  }
Example #20
0
 public static void main(String[] args) {
   System.err.println("Checking FSL path in " + args[0]);
   StringBuffer bf = new StringBuffer();
   try {
     FileReader fr = new FileReader(args[0]);
     int c;
     do {
       c = fr.read();
       bf.append((char) c);
     } while (c != -1);
     FSLNSResolver nsr = new FSLNSResolver();
     nsr.addPrefixBinding("a", "http://a#");
     nsr.addPrefixBinding("b", "http://b#");
     nsr.addPrefixBinding("c", "http://c#");
     nsr.addPrefixBinding("d", "http://d#");
     nsr.addPrefixBinding("e", "http://e#");
     nsr.addPrefixBinding("f", "http://f#");
     nsr.addPrefixBinding("n", "http://n#");
     nsr.addPrefixBinding("dc", "http://dc#");
     nsr.addPrefixBinding("xsd", "http://xsd#");
     nsr.addPrefixBinding("rdf", "http://rdf#");
     nsr.addPrefixBinding("foaf", "http://foaf#");
     nsr.addPrefixBinding("r", "http://r#");
     nsr.addPrefixBinding("", "http://DD#"); // default NS
     System.out.println(
         "serialization:  "
             + FSLPath.pathFactory(bf.substring(0, bf.length() - 1), nsr, FSLPath.NODE_STEP)
                 .serialize()
             + "\n");
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  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);
    }
  }
Example #22
0
  /*
   * (non-Javadoc)
   *
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  public void actionPerformed(ActionEvent e) {
    FileReader fr = null;
    try {

      DigitalCircuit cir;
      fr = new FileReader("temp-cir.xml");
      cir = (DigitalCircuit) st.fromXML(fr);

      DigitalWindow win = new DigitalWindow(); // create a new window
      DrawingPad pad = win.getDrawingPad();
      pad.setCircuit(cir);

      MDIWindow.addWindow(win);
      win.show();

      fr.close();
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (Exception e1) {
      try {
        fr.close();
      } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }
    }
  }
Example #23
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner ler = new Scanner(System.in);
    System.out.printf("informe o nome do arquivo de texto: \n");
    String nome = ler.nextLine();
    System.out.printf("\nconteudo do arquivo texto");

    try {
      FileReader arq = new FileReader(nome);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha = lerArq.readLine();

      while (linha != null) {
        System.out.printf("%s\n", linha);
        linha = lerArq.readLine();

        String val1 = linha.substring(0, linha.indexOf(','));
        int a = Integer.parseInt(val1);
        String val2 = linha.substring(linha.indexOf(',') + 1, linha.lastIndexOf(','));
        int b = Integer.parseInt(val2);
        String val3 = linha.substring(linha.lastIndexOf(',') + 1, linha.length());
        int c = Integer.parseInt(val3);
        setValida(new ValidaTriangulo(a, b, c));
      }
      arq.close();
    } catch (IOException e) {
      System.out.printf("erra na abertura do arquivo: %s.n", e.getMessage());
    }
    System.out.println();
  }
Example #24
0
  /**
   * Reads the example file specified by the example tag of a doc member and adds it to the example
   * section of the doc
   *
   * @param doc
   * @throws IOException
   */
  void setExample(Doc doc) throws IOException {
    Tag[] exampleTag = doc.tags("@example");
    if (exampleTag.length > 0) {
      StringBuffer exampleBuffer = new StringBuffer();
      FileReader in;
      int c;
      String[] pathComponents = exampleTag[0].text().split("/");
      String filePath =
          exampleTag[0].text() + "/" + pathComponents[pathComponents.length - 1] + ".pde";
      in = new FileReader(new File(exampleFolder, filePath));

      while ((c = in.read()) != -1) {
        if ((char) c == '<') {
          exampleBuffer.append("&lt;");
        } else {
          exampleBuffer.append((char) c);
        }
      }

      in.close();

      String exampleString = exampleBuffer.toString();

      EXAMPLE_TAG.setContent(exampleString);

    } else {
      EXAMPLE_TAG.setContent("None available");
    }
  }
  /**
   * Read the available profiles from the internal XML file and return them as collection.
   *
   * @return returns a list of <code>CustomProfile</code> or <code>null</code>
   */
  private List<Profile> readOldForCompatibility(IScopeContext instanceScope) {

    // in 3.0 M9 and less the profiles were stored in a file in the plugin's meta data
    final String STORE_FILE = "code_formatter_profiles.xml"; // $NON-NLS-1$

    File file = JavaPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
    if (!file.exists()) return null;

    try {
      // note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
      final FileReader reader = new FileReader(file);
      try {
        List<Profile> res = readProfilesFromStream(new InputSource(reader));
        if (res != null) {
          for (int i = 0; i < res.size(); i++) {
            fProfileVersioner.update((CustomProfile) res.get(i));
          }
          writeProfiles(res, instanceScope);
        }
        file.delete(); // remove after successful write
        return res;
      } finally {
        reader.close();
      }
    } catch (CoreException e) {
      JavaPlugin.log(e); // log but ignore
    } catch (IOException e) {
      JavaPlugin.log(e); // log but ignore
    }
    return null;
  }
Example #26
0
  public static String getFooter(String context) {
    try {
      FileReader fileReader =
          new FileReader(findResourceOnFileSystem("servletResponseTemplate.htm"));
      BufferedReader buffread = new BufferedReader(fileReader);
      String templateFile = "", line;
      StringBuffer SBreader = new StringBuffer();
      while ((line = buffread.readLine()) != null) {
        SBreader.append(line).append("\n");
      }
      fileReader.close();
      buffread.close();
      templateFile = SBreader.toString();
      templateFile =
          templateFile.replaceAll(
              "BOTTOMGRAPHIC", CommonConfiguration.getURLToFooterGraphic(context));

      int end_header = templateFile.indexOf("INSERT_HERE");
      return (templateFile.substring(end_header + 11));
    } catch (Exception e) {
      // out.println("I couldn't find the template file to read from.");
      e.printStackTrace();
      String error =
          "An error occurred while attempting to read from an HTML template file. This probably will not affect the success of the operation you were trying to perform.</p></body></html>";
      return error;
    }
  }
  private int countTexVerts(String filepath) {
    int texVertCount = 0; // The running total of how many texture verticies are in the file
    String line; // This will hold individual lines from the file as it is being read
    // Unfortunately, the readLine() method will occasionally throw an IOException,
    // so it must be inside this try-catch block...just in case
    try {
      FileReader fr = new FileReader(filepath); // First, setup the file for reading
      BufferedReader objFile =
          new BufferedReader(fr); // The setup a BufferedReader for things like readLine
      line = objFile.readLine(); // Read the first line in the file
      // readLine sets line to null when it has reached the end of the file
      // so continue to read until then.
      while (line != null) {
        // No sense in checking the line if it's blank...besides, the program
        // crashes if you don't check for this first :-)
        // Also, we ONLY want to count lines that begin with "vt" as specified
        // by the OBJ Specification
        if (line.length() > 0)
          if ((line.charAt(0) == 'v') && (line.charAt(1) == 't')) texVertCount++;

        // Grab the next line in the file
        line = objFile.readLine();
      } // end while
      // Done with the files for now, so we close them
      objFile.close();
      fr.close();
    } // end try
    catch (IOException exception) {
      System.out.println("Error reading texture coordinates from file: " + filepath);
    } // end catch
    // System.out.println("\n" + texVertCount + " texture vertices found");
    return texVertCount;
  } // end countTexVerts method
Example #28
0
  public HashMap<String, FoodRating> readFoodFile(String filePath) throws IOException {
    HashMap<String, FoodRating> foodRatingHashMap = new HashMap<>();

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(filePath).getFile());
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line;

    while ((line = br.readLine()) != null) {
      String[] tmp = line.split("[ \t]");
      if (!foodRatingHashMap.containsKey(tmp[0] + " " + tmp[1])) {
        foodRatingHashMap.put(
            tmp[0] + " " + tmp[1], new FoodRating(tmp[0], tmp[1], Double.parseDouble(tmp[2]), 1));
      } else {
        FoodRating foodRating = foodRatingHashMap.get(tmp[0] + " " + tmp[1]);
        foodRating.setScore(
            lbnci.calculateLBNCI(
                foodRating.getScore(), foodRating.getNoOfOccurance(), Double.parseDouble(tmp[2])));
        foodRating.setNoOfOccurance(foodRating.getNoOfOccurance() + 1);
        foodRatingHashMap.put(tmp[0] + " " + tmp[1], foodRating);
      }
    }
    br.close();
    fr.close();
    return foodRatingHashMap;
  }
 public int countMaterials(String fileNameList, String filepath) {
   int matCount = 0;
   String line;
   FileReader fr;
   BufferedReader mtlFile;
   StringTokenizer fileNames = new StringTokenizer(fileNameList.toString());
   try {
     while (fileNames.hasMoreTokens()) {
       fr =
           new FileReader(
               filepath.substring(0, (filepath.length() - objName.length()))
                   + fileNames.nextToken());
       mtlFile = new BufferedReader(fr);
       line = mtlFile.readLine();
       while (line != null) {
         if (line.length() > 6) {
           if (line.substring(0, 6).toLowerCase().compareTo("newmtl") == 0) matCount++;
         }
         line = mtlFile.readLine();
       }
       mtlFile.close();
       fr.close();
     }
   } catch (FileNotFoundException exception) {
     System.out.println("Error opening material library for counting");
     return 0;
   } catch (IOException exception) {
     System.out.println("Error counting materials from material library");
     return 0;
   }
   // DEBUG
   System.out.println(matCount + " materials found");
   // END DEBUG
   return matCount;
 } // end countMaterials
Example #30
0
  /* (non-Javadoc)
   * @see org.collectionspace.JSONStore#retrieveJson(java.lang.String)
   */
  public JSONObject retrieveJSON(String filePath, JSONObject restrictions)
      throws ExistException, UnderlyingStorageException, UnimplementedException {
    // XXX hack: support views properly
    String XXXCHOP = "/view";
    String XXXCHOP2 = "/refs";

    if (filePath.endsWith(XXXCHOP))
      filePath = filePath.substring(0, filePath.length() - XXXCHOP.length());
    if (filePath.endsWith(XXXCHOP2)) return new JSONObject();
    if (idRequest(filePath)) return id.retrieveJSON(filePath, restrictions);
    File jsonFile = fileFromPath(filePath);
    if (!jsonFile.exists()) {
      throw new ExistException("No such file: " + filePath);
    }
    try {
      FileReader r = new FileReader(jsonFile);
      String data = IOUtils.toString(r);
      r.close();
      JSONObject jsonObject = new JSONObject(data);
      return jsonObject;
    } catch (IOException ioe) {
      return new JSONObject(); // XXX
    } catch (JSONException je) {
      return new JSONObject(); // XXX
    }
  }