Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }
Пример #2
0
  public static void main(String[] args) throws Exception {
    System.out.println("hello from Customer.java");

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("customerPU");
    EntityManager manager = factory.createEntityManager();
    Query q1 = manager.createQuery("SELECT COUNT(c) FROM Customer c");
    Long count = (Long) q1.getSingleResult();
    if (count == 0) {
      // record is empty, read from data.txst
      System.out.println("record empty, read from data.txt...");
      // try {
      FileReader fr = new FileReader("data.txt");
      BufferedReader br = new BufferedReader(fr);
      String s;
      while ((s = br.readLine()) != null) {

        // System.out.println(s);
        // split the string s
        Object[] items = s.split("\\|");
        // store in string list
        // List<String> itemList= new ArrayList<String>(Arrays.asList(items));
        // string list converted to array

        // Object[] itemArray = itemList.toArray();
        // insert data into database table
        manager.getTransaction().begin();
        Customer c = new Customer();

        // add email
        c.setEmail((String) items[0]);

        // add pass
        c.setPass((String) items[1]);

        // add name
        c.setName((String) items[2]);

        // add address
        c.setAddress((String) items[3]);

        // add yob
        c.setYob((String) items[4]);

        // change to managed state
        manager.persist(c);
        manager.getTransaction().commit();
      }
      fr.close();
    }

    // display the records
    Query q2 = manager.createNamedQuery("Customer.findAll");
    List<Customer> customers = q2.getResultList();
    for (Customer c : customers) {
      System.out.println(c.getName() + ", " + c.getEmail());
    }

    manager.close();
    factory.close();
  }
Пример #3
0
  public static void main(String[] args) throws IOException {

    // Instantiate Objects
    FileReader fr = new FileReader("Accounts.txt");
    PrintWriter pw = new PrintWriter("CurrentAccounts.txt");
    Scanner console = new Scanner(fr);

    // Pull information from Accounts.txt into Strings
    String fullName = console.next();
    String lastName = fullName.substring(0, 9);
    String firstName = fullName.substring(10, 17);
    String accountBalance = console.next();
    String sWholeValue = accountBalance.substring(0, 4);
    String sDecimalValue = accountBalance.substring(5, 8);

    // Convert accountBalance from one string variable into two integer variables
    int wholeValue = Integer.parseInt(sWholeValue);
    int decimalValue = Integer.parseInt(sDecimalValue);

    // Write
    pw.printf("%15s %14s%06d%06d", firstName, lastName, wholeValue, decimalValue);

    // Close Streams
    fr.close();
    pw.close();
  }
Пример #4
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);
    }
  }
Пример #5
0
 public static void createNgramsFromFolder(
     File input_folder, File output_folder, int ngram_value) {
   Stack<File> stack = new Stack<File>();
   stack.push(input_folder);
   while (!stack.isEmpty()) {
     File child = stack.pop();
     if (child.isDirectory()) {
       for (File f : child.listFiles()) stack.push(f);
     } else if (child.isFile()) {
       try {
         System.out.println("Processing: " + child.getAbsolutePath());
         FileReader fr = new FileReader(child.getAbsolutePath());
         FileWriter outputFile = new FileWriter(output_folder + "/file" + file_no);
         BufferedReader br = new BufferedReader(fr);
         String readline = "";
         while ((readline = br.readLine()) != null) {
           String[] words = readline.split("\\s+");
           for (int i = 0; i < words.length - ngram_value + 1; i++) {
             String ngram = "";
             for (int j = 0; j < ngram_value; j++) ngram = ngram + " " + words[i + j];
             outputFile.write(ngram + "\n");
           }
         }
         file_no++;
         outputFile.close();
         br.close();
         fr.close();
       } catch (Exception e) {
         System.out.println("File not found:" + e);
       }
     }
   }
 }
Пример #6
0
  public static void main(String[] args) throws IOException {
    WordInfo[] wordTable = new WordInfo[MaxWords];

    FileReader in = new FileReader("passage.txt");
    PrintWriter out = new PrintWriter(new FileWriter("output.txt"));

    for (int h = 0; h < MaxWords; h++) wordTable[h] = new WordInfo("", 0);
    int numWords = 0;

    String word = getWord(in).toLowerCase();
    while (!word.equals("")) {
      int loc = binarySearch(word, wordTable, 0, numWords - 1);
      if (word.compareTo(wordTable[loc].word) == 0) wordTable[loc].incrFreq();
      else // this is a new word
      if (numWords < MaxWords) { // if table is not full
        addToList(word, wordTable, loc, numWords - 1);
        ++numWords;
      } else out.printf("'%s' not added to table\n", word);
      word = getWord(in).toLowerCase();
    }

    printResults(out, wordTable, numWords);
    in.close();
    out.close();
  } // end main
Пример #7
0
  public static Set<RepairedCell> readTruth(String fileRoute) {
    File file = new File(fileRoute);
    Set<RepairedCell> truth = new HashSet<RepairedCell>();

    if (!file.exists()) {
      System.out.println(fileRoute + "文件不存在,无法测试!");
      return truth;
    }
    try {
      FileReader fr = new FileReader(file);
      BufferedReader br = new BufferedReader(fr);

      String line = null;
      while (null != (line = br.readLine())) {
        String[] paras = line.split(",");
        RepairedCell cell = null;
        if (paras.length == 2) {
          cell = new RepairedCell(Integer.parseInt(paras[0]), paras[1], "");
        } else {
          cell = new RepairedCell(Integer.parseInt(paras[0]), paras[1], paras[2]);
        }
        truth.add(cell);
      }

      br.close();
      fr.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return truth;
  }
  public static void main(String args[]) throws Exception {
    HashSet<String> hs = new HashSet<String>();

    FileReader fr1 = new FileReader("sample.txt");
    BufferedReader br = new BufferedReader(fr1);
    String s;
    while ((s = br.readLine()) != null) {
      hs.add(s);
    }
    fr1.close();
    FileReader fr2 = new FileReader("input.txt");
    br = new BufferedReader(fr2);
    while ((s = br.readLine()) != null) {

      Scanner ip = new Scanner(s);

      String word;
      while (ip.hasNext()) {
        word = ip.next();
        if (hs.contains(word)) ;
        else System.out.print(word + " ");
      }
    }
    fr2.close();
  }
Пример #9
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();
  }
Пример #10
0
 public static void main(String[] args) {
   try {
     if (args.length != 1) throw new IllegalArgumentException("Wrong number of arguments");
     FileReader in = new FileReader(args[0]);
     HardcopyWriter out = null;
     Frame f = new Frame("PrintFile: " + args[0]);
     f.setSize(200, 50);
     f.show();
     try {
       out = new HardcopyWriter(f, args[0], 10, .75, .75, .75, .75);
     } catch (HardcopyWriter.PrintCanceledException e) {
       System.exit(0);
     }
     f.setVisible(false);
     char[] buffer = new char[4096];
     int numchars;
     while ((numchars = in.read(buffer)) != -1) out.write(buffer, 0, numchars);
     out.close();
   } catch (Exception e) {
     System.err.println(e);
     System.err.println("Usage: java HardcopyWriter$PrintFile <filename>");
     System.exit(1);
   }
   System.exit(0);
 }
 private static String fileToString(File f) throws Exception {
   StringWriter output = new StringWriter();
   FileReader input = new FileReader(f);
   char[] buffer = new char[8 * 1024];
   int n = 0;
   while (-1 != (n = input.read(buffer))) {
     output.write(buffer, 0, n);
   }
   return output.toString();
 }
Пример #12
0
 public static String readFile(File file) {
   FileReader r = null;
   try {
     r = new FileReader(file);
     char[] data = new char[(int) file.length()];
     r.read(data);
     return new String(data);
   } catch(IOException e) {
     throw Log.errRTExcept(e);
   } finally {
     close(r);
   }
 }
Пример #13
0
  public static void main(String[] args) {
    // 1. read the inchis into HashMap
    HashMap inchiDict = new HashMap();
    try {
      FileReader inchiDictionary = new FileReader(args[0]);
      BufferedReader inchiDictionaryBR = new BufferedReader(inchiDictionary);
      String line = inchiDictionaryBR.readLine();
      // While more InChIs remain
      while (line != null) {
        String[] spl = line.split("\t"); // split on tab
        inchiDict.put(spl[0], spl[2]); // add the chemkin name as key, and InChI as value
        line = inchiDictionaryBR.readLine();
      }
      inchiDictionary.close();
    } catch (FileNotFoundException e) {
      System.err.println("File was not found!\n");
    } catch (IOException eIO) {
      System.err.println("IO Exception!\n");
    }

    // 2. read the CHEMKIN file, while simultaneously writing a CHEMKIN output file with InChI
    // comments, where available
    try {
      FileReader chemkinOld = new FileReader(args[1]);
      FileWriter chemkinNew = new FileWriter(args[2]);
      BufferedReader chemkinReader = new BufferedReader(chemkinOld);
      BufferedWriter chemkinWriter = new BufferedWriter(chemkinNew);
      String line = chemkinReader.readLine();
      // While more InChIs remain
      while (line != null) {
        String[] spl = line.split(" "); // split on  space
        int len = spl.length;
        // if the last "word" is a 1 and the first word can be found in the dictionary, write a
        // comment line before copying the line; otherwise, just copy the line
        if (spl[len - 1].equals("1") && inchiDict.containsKey(spl[0])) {
          chemkinWriter.write("! [_ SMILES=\"" + inchiDict.get(spl[0]) + "\" _]\n");
        }
        chemkinWriter.write(line + "\n");

        line = chemkinReader.readLine();
      }
      chemkinOld.close();
      chemkinWriter.flush();
      chemkinWriter.close();
      chemkinNew.close();
    } catch (FileNotFoundException e) {
      System.err.println("File was not found!\n");
    } catch (IOException eIO) {
      System.err.println("IO Exception!\n");
    }
  }
Пример #14
0
  public static String getWord(FileReader in) throws IOException {
    // returns the next word found
    final int MaxLen = 255;
    int c, n = 0;
    char[] word = new char[MaxLen];
    // read over non-letters
    while (!Character.isLetter((char) (c = in.read())) && (c != -1)) ;
    // empty while body
    if (c == -1) return ""; // no letter found

    word[n++] = (char) c;
    while (Character.isLetter(c = in.read())) if (n < MaxLen) word[n++] = (char) c;
    return new String(word, 0, n);
  } // end getWord
  // Read the patron file, and parse data into strings
  private void config_read(String fileParam) {
    File inputFile = new File(fileParam);

    if (inputFile == null || !inputFile.exists()) {
      System.out.println("parameter " + fileParam + " file doesn't exists!");
      System.exit(-1);
    }
    // begin the configuration read from file
    try {
      FileReader file_reader = new FileReader(inputFile);
      BufferedReader buf_reader = new BufferedReader(file_reader);
      // FileWriter file_write = new FileWriter(outputFile);

      String line;

      do {
        line = buf_reader.readLine();
      } while (line.length() == 0); // avoid empty lines for processing -> produce exec failure
      String out[] = line.split("algorithm = ");
      // alg_name = new String(out[1]); //catch the algorithm name
      // input & output filenames
      do {
        line = buf_reader.readLine();
      } while (line.length() == 0);
      out = line.split("inputData = ");
      out = out[1].split("\\s\"");
      input_train_name = new String(out[0].substring(1, out[0].length() - 1));
      input_test_name = new String(out[1].substring(0, out[1].length() - 1));
      if (input_test_name.charAt(input_test_name.length() - 1) == '"')
        input_test_name = input_test_name.substring(0, input_test_name.length() - 1);

      do {
        line = buf_reader.readLine();
      } while (line.length() == 0);
      out = line.split("outputData = ");
      out = out[1].split("\\s\"");
      output_train_name = new String(out[0].substring(1, out[0].length() - 1));
      output_test_name = new String(out[1].substring(0, out[1].length() - 1));
      if (output_test_name.charAt(output_test_name.length() - 1) == '"')
        output_test_name = output_test_name.substring(0, output_test_name.length() - 1);

      file_reader.close();

    } catch (IOException e) {
      System.out.println("IO exception = " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }
Пример #16
0
  public static void lookingCode() {

    int procura = 0;
    boolean entrou = false;

    do {
      procura = Entrada.leiaInt("Digite o código da carta: ");
    } while (procura < 0 || procura > 32);

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

      while (linha != null) {

        // procura na string '.'
        if (linha.toLowerCase().contains(".".toLowerCase())) {

          // separ em um array a linha que tem o nome do personagem ex: 1.CARLOS
          String columnArray[] = linha.split(Pattern.quote("."));

          // testa se o codigo é o que ele procura
          if (procura == Integer.parseInt(columnArray[0])) {

            // achou o codigo que ele procura
            entrou = true;
          }
        }

        // testa se a linha é igual a * se for ele já não é mais o personagem que procuramos
        if (linha.equals("*")) {
          entrou = false;
        }

        // mostra as inforamações do personagem
        if (entrou) {
          System.out.println(linha);
        }

        linha = lerArq.readLine();
      }

      arq.close();
    } catch (IOException e) {
      System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
    }
  }
Пример #17
0
    public static void main(String[] args) {
        ArrayList instances = null;
        ArrayList distances = null;
        ArrayList neighbors = null;
        WSAction.Action classification = null;
        Instance classificationInstance = null;
        FileReader reader = null;
        int numRuns = 0, truePositives = 0, falsePositives = 0, falseNegatives = 0, trueNegatives = 0;
        double precision = 0, recall = 0, fMeasure = 0;

        falsePositives = 1;

        reader = new FileReader(PATH_TO_DATA_FILE);
        instances = reader.buildInstances();

        do {
            classificationInstance = extractIndividualInstance(instances);

            distances = calculateDistances(instances, classificationInstance);
            neighbors = getNearestNeighbors(distances);
            classification = determineMajority(neighbors);

            System.out.println("Gathering " + K + " nearest neighbors to:");
            printClassificationInstance(classificationInstance);

            printNeighbors(neighbors);
            System.out.println("\nExpected situation result for instance: " + classification.toString());

            if(classification.toString().equals(((WSAction)classificationInstance.getAttributes().get(WSACTION_INDEX)).getAction().toString())) {
                truePositives++;
            }
            else {
                falseNegatives++;
            }
            numRuns++;

            instances.add(classificationInstance);
        } while(numRuns &lt; NUM_RUNS);

        precision = ((double)(truePositives / (double)(truePositives + falsePositives)));
        recall = ((double)(truePositives / (double)(truePositives + falseNegatives)));
        fMeasure = ((double)(precision * recall) / (double)(precision + recall));

        System.out.println("Precision: " + precision);
        System.out.println("Recall: " + recall);
        System.out.println("F-Measure: " + fMeasure);
        System.out.println("Average distance: " + (double)(averageDistance / (double)(NUM_RUNS * K)));
    }
Пример #18
0
 // Apparently, fast load text file ? "readin" function in original text
 // http://users.cs.cf.ac.uk/O.F.Rana/jdc/swing-nov7-01.txt
 public static synchronized void loadFileToPane(String fname, JTextComponent pane) {
   FileReader fr = null;
   try {
     fr = new FileReader(fname);
     pane.read(fr, null);
     fr.close();
   } catch (IOException ex) {
     mylogger.log(Level.SEVERE, "Error while loading: ", ex);
   } finally {
     try {
       fr.close();
     } catch (IOException ex) {
       mylogger.log(Level.SEVERE, "Error while loading: ", ex);
     }
   }
 }
  private static int runReplacement(
      String env, ConfigTokens conf, String scope, List<File> toProcess) {
    int errorCount = 0;
    for (File xmlFile : toProcess) {
      try {
        Document xmlDoc = FileReader.getXMLDocument(xmlFile);
        Policy tokens;
        if (StringUtils.equalsIgnoreCase(scope, "proxy")) {
          tokens = conf.getConfigbyEnv(env).getProxyFileNameMatch(xmlFile.getName());
        } else if (StringUtils.equalsIgnoreCase(scope, "policy")) {
          tokens = conf.getConfigbyEnv(env).getPolicyFileNameMatch(xmlFile.getName());
        } else if (StringUtils.equalsIgnoreCase(scope, "target")) {
          tokens = conf.getConfigbyEnv(env).getTargetFileNameMatch(xmlFile.getName());
        } else {
          continue;
        } // === N E X T ===
        xmlDoc = replaceTokens(xmlDoc, tokens);
        DOMSource source = new DOMSource(xmlDoc);
        StreamResult result = new StreamResult(xmlFile);
        tltf.get().transform(source, result);
      } catch (Exception e) {
        logger.error("Error processing " + xmlFile.getName(), e);
        errorCount++;
      }
    }

    return errorCount;
  }
Пример #20
0
  static void addLugarFicheroLOC(String fichero, Lugar lugar) {

    try {
      File f = new File(fichero);
      if (!f.exists()) f.createNewFile();

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

      String linea;
      ArrayList lineas = new ArrayList();

      do {
        linea = br.readLine();
        if (linea != null) lineas.add(linea);
        else break;
      } while (true);
      br.close();
      fr.close();
      linea =
          ""
              + lugar.nombre
              + ":"
              + lugar.latitud
              + ":"
              + lugar.longitud
              + ":"
              + lugar.altitud
              + ":"
              + lugar.offsetUTC;
      lineas.add(linea);

      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) {

    } catch (IOException e) {

    }
  }
Пример #21
0
 String loadFile(File file) {
   try {
     FileReader fr = new FileReader(file);
     BufferedReader br = new BufferedReader(fr);
     StringBuffer str = new StringBuffer();
     char[] buffer = new char[1024];
     int read;
     while ((read = br.read(buffer)) != -1) {
       str.append(buffer, 0, read);
     }
     fr.close();
     return str.toString();
   } catch (IOException e) {
     e.printStackTrace(System.out);
   }
   return "";
 }
Пример #22
0
  /**
   * Loads an OLS data file from the given file.
   *
   * @param aFile the file to load as OLS data, cannot be <code>null</code>.
   * @throws IOException in case of I/O problems.
   */
  public void openDataFile(final File aFile) throws IOException {
    final FileReader reader = new FileReader(aFile);

    try {
      final Project tempProject = this.projectManager.createTemporaryProject();
      OlsDataHelper.read(tempProject, reader);

      setChannelLabels(tempProject.getChannelLabels());
      setCapturedData(tempProject.getCapturedData());
      setCursorData(tempProject.getCursorPositions(), tempProject.isCursorsEnabled());
    } finally {
      reader.close();

      zoomToFit();

      updateActions();
    }
  }
Пример #23
0
  public static List<KAFSentence> read() throws Exception {
    List<KAFSentence> list = new Vector<KAFSentence>();
    FileReader fr = null;
    BufferedReader br = null;
    int pos, endpos;

    fr = new FileReader(f);
    br = new BufferedReader(fr);
    String line = null;
    int sent_id = 0;
    String token = null;
    KAFSentence KAF_sen = null;
    KAFToken KAF_tkn = null;

    while ((line = br.readLine()) != null) {
      if (line.indexOf("<wf") == 0) {
        String pattern = "sent=\"";
        pos = line.indexOf(pattern);
        pos = pos + pattern.length();
        endpos = line.indexOf('"', pos);
        sent_id = Integer.parseInt(line.substring(pos, endpos));

        pos = line.indexOf('>', pos);
        endpos = line.indexOf('<', pos);
        token = line.substring(pos, endpos);

        KAF_tkn = new KAFToken();
        KAF_tkn.assignToken(token);

        if (list.size() < sent_id) {
          KAF_sen = new KAFSentence();
          KAF_sen.addToken(KAF_tkn);
          list.add(KAF_sen);
        } else {
          KAF_sen.addToken(KAF_tkn);
        }
      }
    }

    br.close();
    fr.close();

    return list;
  }
  public static JSmoothModelBean load(File fin) throws IOException {
    FileReader fr = new FileReader(fin);
    try {
      JSmoothModelBean jobj = new JSmoothModelBean();
      String INVALID = "INVALID";
      jobj.setSkeletonName(INVALID);
      JOXBeanReader jbr = new JOXBeanReader(fr);
      jbr.readObject(jobj);
      jbr.close();
      fr.close();

      if (jobj.getSkeletonName() == INVALID) {
        throw new Exception("Not a JOX File");
      }
      //		System.out.println("Loaded jobj " + jobj + " = " + jobj.getJarLocation());
      if ((jobj.getJarLocation() != null) && (jobj.getJarLocation().length() > 0)) {
        jobj.setEmbeddedJar(true);
        //			System.out.println("Set embeddedjar to " + jobj.getEmbeddedJar());
      }

      return jobj;

    } catch (Exception exc) {
      fr.close();

      try {
        FileInputStream fis = new FileInputStream(fin);
        XMLDecoder dec = new XMLDecoder(fis);
        JSmoothModelBean xobj = (JSmoothModelBean) dec.readObject();
        fis.close();

        if ((xobj.getJarLocation() != null) && (xobj.getJarLocation().length() > 0))
          xobj.setEmbeddedJar(true);

        return xobj;

      } catch (Exception exc2) {
        exc2.printStackTrace();
        throw new IOException(exc2.toString());
      }
    }
  }
Пример #25
0
  public static void readFile() {

    try {

      FileReader arq = new FileReader(FileManenger.fileName);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha =
          lerArq
              .readLine(); // lê a primeira linha a variável "linha" recebe o valor "null" quando o
                           // processo  de repetição atingir o final do arquivo texto
      while (linha != null) {
        System.out.println(linha);
        linha = lerArq.readLine(); // lê da segunda até a última linha
      }
      arq.close();

    } catch (IOException e) {
      System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
    }
  }
Пример #26
0
  public BinaryDictionary(File wordList) throws FileNotFoundException {
    try {
      if (!wordList.exists())
        throw new FileNotFoundException("Error reading: " + wordList.getName());

      FileReader fr = new FileReader(wordList);
      BufferedReader br = new BufferedReader(fr);
      String word;

      // Populate list of words.
      while ((word = br.readLine()) != null) {
        words.add(word);
      }

      br.close();
      fr.close();
    } catch (IOException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
Пример #27
0
  static void reader(ArrayList<String> nameFile) throws Exception {

    BufferedReader in = null;
    FileReader file = null;
    try {
      if (isInput) {
        for (int j = 0; j < nameFile.size(); j++) { // read from files
          int numberWord = 0;
          file = new FileReader(nameFile.get(j));
          in = new BufferedReader(file);
          while (in.ready()) {
            String currentLine = in.readLine();
            queue.put(new Pair(currentLine, j, numberWord));
            numberWord++;
          }
          in.close();
          file.close();
        }
      } else { // read from stdin
        in = new BufferedReader(new InputStreamReader(System.in));
        String currentLine;
        int numberWord = 0;
        while ((currentLine = in.readLine()) != null) {
          queue.put(new Pair(currentLine, 1, numberWord));
          numberWord++;
        }
        in.close();
      }
    } finally {
      if (in != null) {
        in.close();
      }
      if (file != null) {
        file.close();
      }
    }
    for (int i = 0; i < numberThreads; i++) {
      queue.put(STOP);
    }
  }
  public void replaceVariable() throws IOException {
    Closer closer = Closer.create();
    try {
      FileReader fReader = new FileReader();
      List<String> content = fReader.getContent(FictionURL);
      Properties indexOrderProperties = getIndexOrder();
      List<String> natureOrderList = getNatureOrder(propertiesURL);
      List<String> charOrderList = getCharOrder(natureOrderList);
      Pattern p = Pattern.compile("\\$(\\w+)\\((\\d+)\\)");
      OutputStreamWriter streamWriter =
          closer.register(new OutputStreamWriter(new FileOutputStream("result.txt"), "UTF-8"));

      for (String tempStr : content) {
        Matcher m = p.matcher(tempStr);
        while (m.find()) {
          String orderName = m.group(1);
          String num = m.group(2);
          int listSize = natureOrderList.size();
          if (orderName.equals("natureOrder"))
            tempStr = tempStr.replace(m.group(), natureOrderList.get(Integer.parseInt(num)));
          else if (orderName.equals("charOrder"))
            tempStr = tempStr.replace(m.group(), charOrderList.get(Integer.parseInt(num)));
          else if (orderName.equals("charOrderDESC"))
            // 倒序为正序下标为:下标位置(集合总数-1)-倒序位置
            tempStr =
                tempStr.replace(m.group(), charOrderList.get(listSize - 1 - Integer.parseInt(num)));
          else if (orderName.equals("indexOrder")) {
            if (indexOrderProperties.getProperty(num) != null)
              tempStr = tempStr.replace(m.group(), indexOrderProperties.getProperty(num));
            else tempStr = tempStr.replace(m.group(), "null");
          }
        }
        streamWriter.write(tempStr + "\n");
        System.out.println(tempStr);
      }
    } finally {
      closer.close();
    }
  }
  public static void configurePackage(String env, File configFile) throws Exception {
    Transformer transformer = tltf.get();

    // get the list of files in proxies folder
    XMLFileListUtil listFileUtil = new XMLFileListUtil();

    ConfigTokens conf = FileReader.getBundleConfigs(configFile);

    Map<String, List<File>> filesToProcess = new HashMap<String, List<File>>();
    filesToProcess.put("proxy", listFileUtil.getProxyFiles(configFile));
    filesToProcess.put("policy", listFileUtil.getPolicyFiles(configFile));
    filesToProcess.put("target", listFileUtil.getTargetFiles(configFile));

    doTokenReplacement(env, conf, filesToProcess);

    // special case ...
    File proxyFile = listFileUtil.getAPIProxyFiles(configFile).get(0);
    Document xmlDoc =
        FileReader.getXMLDocument(proxyFile); // there would be only one file, at least one file

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expression = xpath.compile("/APIProxy/Description");

    NodeList nodes = (NodeList) expression.evaluate(xmlDoc, XPathConstants.NODESET);
    if (nodes.item(0).hasChildNodes()) {
      // sets the description to whatever is in the <proxyname>.xml file
      nodes.item(0).setTextContent(expression.evaluate(xmlDoc));
    } else {
      // if Description is empty, then it reverts back to appending the username, git hash, etc
      nodes.item(0).setTextContent(getComment(proxyFile));
    }

    DOMSource source = new DOMSource(xmlDoc);
    StreamResult result = new StreamResult(proxyFile);
    transformer.transform(source, result);
  }
Пример #30
0
  /** Get a grammar mentioned on the command-line and any delegates */
  public Grammar getRootGrammar(String grammarFileName) throws IOException {
    // StringTemplate.setLintMode(true);
    // grammars mentioned on command line are either roots or single grammars.
    // create the necessary composite in case it's got delegates; even
    // single grammar needs it to get token types.
    CompositeGrammar composite = new CompositeGrammar();
    Grammar grammar = new Grammar(this, grammarFileName, composite);
    composite.setDelegationRoot(grammar);
    FileReader fr = null;
    File f = null;

    if (haveInputDir) {
      f = new File(inputDirectory, grammarFileName);
    } else {
      f = new File(grammarFileName);
    }

    // Store the location of this grammar as if we import files, we can then
    // search for imports in the same location as the original grammar as well as in
    // the lib directory.
    //
    parentGrammarDirectory = f.getParent();

    if (grammarFileName.lastIndexOf(File.separatorChar) == -1) {
      grammarOutputDirectory = ".";
    } else {
      grammarOutputDirectory =
          grammarFileName.substring(0, grammarFileName.lastIndexOf(File.separatorChar));
    }
    fr = new FileReader(f);
    BufferedReader br = new BufferedReader(fr);
    grammar.parseAndBuildAST(br);
    composite.watchNFAConversion = internalOption_watchNFAConversion;
    br.close();
    fr.close();
    return grammar;
  }