void applyAdditionalStrategies() {
    //        if (saveLongTail) {
    /*            try {
        longTailWriter = Files.newBufferedWriter(
                GibbsConfigurationManager.getPath(myFolder + "/" + IEnsemble.LONGTAIL_FILE),
                Charset.defaultCharset(), StandardOpenOption.CREATE,
                opt.isOld() ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING,
                StandardOpenOption.WRITE);
    } catch (Exception e) {
        System.out.println("ERROR: Can't create " + LONGTAIL_FILE + " for " + myFolder);
    }*/
    //        }

    // open current point adiitonal parameters logging "2box.dat"
    try {
      additionalStateWriter =
          Files.newBufferedWriter(
              GibbsConfigurationManager.getPath(myFolder + "/" + GibbsEnsemble.GIBBS_STATE_FILE),
              Charset.forName("UTF-8"),
              StandardOpenOption.CREATE,
              myEnsemble.opt.isOld()
                  ? StandardOpenOption.APPEND
                  : StandardOpenOption.TRUNCATE_EXISTING,
              StandardOpenOption.WRITE);
    } catch (Exception e) {
      System.out.println(
          "ERROR: Can't create " + GibbsEnsemble.GIBBS_STATE_FILE + " for " + myFolder);
    }
  }
  public static void outputDoctorSentimentReviewsToJson(
      Map<Integer, List<SentimentReview>> docToSentimentReviews, String updatedDatasetPath) {

    ObjectMapper mapper = new ObjectMapper();
    try {
      Files.deleteIfExists(Paths.get(updatedDatasetPath));
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    int count = 1;
    for (Integer docId : docToSentimentReviews.keySet()) {
      try (BufferedWriter writer =
          Files.newBufferedWriter(
              Paths.get(updatedDatasetPath),
              StandardOpenOption.CREATE,
              StandardOpenOption.APPEND)) {
        if (count > 1) writer.newLine();
        DoctorSentimentReview doctorReview =
            new DoctorSentimentReview(docId, docToSentimentReviews.get(docId));
        mapper.writeValue(writer, doctorReview);

        count++;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    System.out.println("Num of Outputed docIDs " + count);
  }
  @Override
  public void execute() throws BuildException {
    Properties properties = new Properties();
    Path path = file.toPath();

    if (file.exists()) {
      try {
        properties.load(Files.newBufferedReader(path, StandardCharsets.UTF_8));
      } catch (IOException e) {
        throw new BuildException(e);
      }
    }

    Version version = new Version(properties.getProperty(PROPERTY, "0.0.0"));

    version.increment(importance);

    String value = version.toString();

    properties.setProperty(PROPERTY, value);
    getProject().setProperty(PROPERTY, value);

    try {
      properties.store(Files.newBufferedWriter(path, StandardCharsets.UTF_8), null);
    } catch (IOException e) {
      throw new BuildException(e);
    }
  }
  public static void decodeURI(Properties config, String toDecode, String decoded) {

    LOG.info("Start to decode URIs...");

    final BufferedReader reader;
    final BufferedWriter writer;
    final Path src =
        Paths.get(config.getProperty("org.dbpedia.spotlight.data." + toDecode, "").trim());
    final Path dst =
        Paths.get(config.getProperty("org.dbpedia.spotlight.data." + decoded, "").trim());
    String line;

    try {
      reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
      writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);

      while ((line = reader.readLine()) != null) {
        line = line.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
        line = line.replaceAll("\\+", "%2B");
        writer.write(URLDecoder.decode(line, "UTF-8"));
        writer.newLine();
      }
      writer.close();

      LOG.info("Done");

    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
  public void writeData(Path path, String uname, String upass, String ulocation, String udatabase) {
    Charset charset = Charset.forName("US-ASCII");
    Path filepath = Paths.get("resources/system/" + path);
    deleteFile(path);
    //         try(OutputStream out = new BufferedOutputStream(Files.newOutputStream(filepath,
    // CREATE))){
    try (BufferedWriter out =
        new BufferedWriter(Files.newBufferedWriter(filepath, charset, CREATE))) {
      String username = uname;
      String pass = upass;
      String lc = ulocation;
      String db = udatabase;

      //       Byte[] user = ;
      //             out.write(username.getBytes(), 0   , username.length());
      //             out.write(newline.getBytes());
      //             out.write(pass.getBytes());
      //               out.write(newline.getBytes());
      //             out.write(lc.getBytes());
      //               out.write(newline.getBytes());
      //             out.write(db.getBytes());
      out.write(username, 0, username.length());
      out.newLine();
      out.write(pass);
      out.newLine();
      out.write(lc);
      out.newLine();
      out.write(db);

      //             JOptionPane.showMessageDialog(null, "Database.dat file create Succesfully");
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(null, ioe + " from createdatabasefile");
    }
  }
 public void generate(Path output) throws IOException, GraphUtilException, GenerationException {
   final String className = output.getFileName().toString().replaceFirst("\\.java$", "");
   try (PrintWriter out =
       new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
     generate(className, out);
   }
 }
Exemple #7
0
 /** 读写文件的优化 */
 @Test
 public void testReadAndWriter() {
   // StandardCharsets.UTF_8
   Path path2 = Paths.get(PATH);
   String string = ParentPath + "\\writer.txt";
   Path path3 = Paths.get(string);
   try {
     Files.createFile(path3);
   } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   try (BufferedReader reader = Files.newBufferedReader(path2, Charset.forName("GBK"));
       BufferedWriter bw =
           Files.newBufferedWriter(path3, Charset.forName("UTF-8"), StandardOpenOption.WRITE)) {
     String line;
     while ((line = reader.readLine()) != null) {
       System.out.println(line);
       bw.write(line);
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemple #8
0
  void storeXml(ParseIndexContext ctx, Path xml) throws IOException {
    Files.createFile(xml);
    PrintWriter p = new PrintWriter(Files.newBufferedWriter(xml, utf8));
    p.print("<?xml version='1.1' encoding='" + NotesRetriever.utf8.name() + "'?><snotes>");

    ctx.list.sort(Comparator.comparing(o1 -> o1.number));
    for (NoteListItem i : ctx.list) {
      p.print("\n<n");
      p.print(" n='" + i.number + "'");
      if (i.mark != null) p.print(" m='" + i.mark + "'");
      p.print(" a='" + i.apparea + "'");
      p.print(" l='" + i.asklangu + "'");
      p.print(" d='" + DateTimeFormatter.ISO_LOCAL_DATE.format(i.date) + "'");
      p.print(" c='" + i.category + "'");
      p.print(" p='" + i.priority + "'");
      if (i.objid != null) p.print(" o='" + i.objid + "'");
      p.print(">" + StringEscapeUtils.escapeXml11(i.title) + "</n>");
    }
    p.flush();
    for (Pair<String, String> a : ctx.lareas) {
      p.print("\n<area rcode='" + a.getKey() + "' value='" + a.getValue() + "'/>");
    }
    p.flush();
    //		p.print("\n<!-- [Statistics]");
    //		if (dsd==0 && dod==0) {
    //			p.print("\tNotes collected: " + q + ", no duplicates found");
    //		} else {
    //			p.print("\nUnique notes collected: " + q);
    //			p.print("\nDuplicate notes with the same date: " + dsd);
    //			p.print("\nDuplocate notes with the other date: " + dod);
    //		}
    //		p.println("\t-->");
    p.print("\n</snotes>");
    p.close();
  }
Exemple #9
0
  public List<RoundTrip> weekendCheckCaxias2Congonhas() throws Exception {
    List<RoundTrip> tripsWithGoodPrice = new ArrayList<>();

    Path logFile = buildLogFile("caxias2congonhas_");
    try (BufferedWriter writter = Files.newBufferedWriter(logFile)) {

      write(
          writter,
          String.format(
              "Searching Flyies from '%s' to '%s' ", startDate.format(DATE), endDate.format(DATE)));

      LocalDate next = startDate;
      do {
        LocalDate friday = next.with(next(DayOfWeek.FRIDAY));
        LocalDate saturday = friday.with(next(DayOfWeek.SATURDAY));
        LocalDate sunday = friday.with(next(DayOfWeek.SUNDAY));
        LocalDate monday = friday.with(next(DayOfWeek.MONDAY));

        tripsWithGoodPrice.add(
            check(writter, CAXIAS, CONGONHAS, friday, ANY, sunday, ANY, PROMO_CODE));
        //                tripsWithGoodPrice.add(check(writter, CAXIAS, CONGONHAS, friday, NIGHT,
        // monday, MORNING, PROMO_CODE));
        tripsWithGoodPrice.add(
            check(writter, CAXIAS, CONGONHAS, saturday, ANY, sunday, ANY, PROMO_CODE));
        //                tripsWithGoodPrice.add(check(writter, CAXIAS, CONGONHAS, saturday,
        // MORNING, monday, MORNING, PROMO_CODE));

        write(writter, "\n");

        next = monday;
      } while (next.compareTo(endDate) < 0);
    }

    return tripsWithGoodPrice.stream().filter(Objects::nonNull).collect(Collectors.toList());
  }
  void saveConfiguration() {
    // create strings list from arrays
    try {
      BufferedWriter writer = Files.newBufferedWriter(myConfigPath, Charset.forName("UTF-8"));
      final double avgEnergy1 = myEnsemble.getAvgEnergy(0);
      final double avgEnergy2 = myEnsemble.getAvgEnergy(1);
      //          first line format:
      //
      // current step, boxBorder, avg. energy 1 (per prtcl), avg density 1, avg. energy 2, avg.
      // density 2, total Gamma
      writer.write(
          ""
              + myEnsemble.getCurrStep()
              + "\t"
              + myEnsemble.getBoxBorder()
              + "\t"
              + long_format.format(avgEnergy1)
              + "\t"
              + long_format.format(myEnsemble.getDensitiesAvg()[0])
              + "\t"
              + long_format.format(avgEnergy2)
              + "\t"
              + long_format.format(myEnsemble.getDensitiesAvg()[1])
              + "\t"
              + short_format.format(myEnsemble.opt.getGamma())
              + "\t");

      writer.newLine();
      writeCoordinates(writer);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("ERROR: failed to save state for " + myFolder);
    }
  }
  @Override
  public boolean addModule(Module module) throws IOException {
    if (module.isDynamic()) {
      if (module.hasIniTemplate()) {
        // warn
        StartLog.warn("%-15s not adding [ini-template] from dynamic module", module.getName());
      }
      return false;
    }

    String mode = "";
    if (module.isTransitive()) {
      mode = "(transitively) ";
    }

    if (module.hasIniTemplate() || !module.isTransitive()) {
      // Create start.d/{name}.ini
      Path ini = startDir.resolve(module.getName() + ".ini");
      StartLog.info("%-15s initialised %sin %s", module.getName(), mode, baseHome.toShortForm(ini));

      try (BufferedWriter writer =
          Files.newBufferedWriter(
              ini,
              StandardCharsets.UTF_8,
              StandardOpenOption.CREATE,
              StandardOpenOption.TRUNCATE_EXISTING)) {
        writeModuleSection(writer, module);
      }
      return true;
    }

    return false;
  }
Exemple #12
0
 public void open(Path path) {
   try {
     if (!Files.exists(path)) path = Files.createFile(path);
     writer = Files.newBufferedWriter(path, charset);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemple #13
0
  private void saveHistory() {
    try (Writer out = Files.newBufferedWriter(historyFile.toPath())) {
      String lineSeparator = System.getProperty("line.separator");

      out.write(getHistory().save().stream().collect(Collectors.joining(lineSeparator)));
    } catch (final IOException exp) {
    }
  }
Exemple #14
0
 public static void writeFile() {
   try (BufferedWriter writer =
       Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
     writer.write("hello2");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemple #15
0
 @Override
 public CharSource createSource(String string) throws IOException {
   checkNotNull(string);
   Path file = createFile();
   try (Writer writer = java.nio.file.Files.newBufferedWriter(file, Charsets.UTF_8)) {
     writer.write(string);
   }
   return MoreFiles.asCharSource(file, Charsets.UTF_8);
 }
Exemple #16
0
  public static void main(String[] args) throws IOException {
    try (Stream<Path> stream = Files.list(Paths.get(""))) {
      String joined =
          stream
              .map(String::valueOf)
              .filter(path -> !path.startsWith("."))
              .sorted()
              .collect(Collectors.joining("; "));
      System.out.println("List: " + joined);
    }

    Path start = Paths.get("");
    int maxDepth = 5;
    try (Stream<Path> stream =
        Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".java"))) {
      String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
      System.out.println("Found: " + joined);
    }

    try (Stream<Path> stream = Files.walk(start, maxDepth)) {
      String joined =
          stream
              .map(String::valueOf)
              .filter(path -> path.endsWith(".java"))
              .sorted()
              .collect(Collectors.joining("; "));
      System.out.println("walk(): " + joined);
    }

    List<String> lines = Files.readAllLines(Paths.get("src/golf.sh"));
    lines.add("puts 'foobar'");
    Path path = Paths.get("src/golf-modified.sh");
    Files.write(path, lines);

    try (Stream<String> stream = Files.lines(path)) {
      stream.filter(line -> line.contains("puts")).map(String::trim).forEach(System.out::println);
    }

    System.out.println("a" == "a");
    System.out.println("a" != new String("a"));
    System.out.println(null != "a");
    System.out.println("a".equals("a"));

    try (BufferedReader reader = Files.newBufferedReader(path)) {
      while (reader.ready()) System.out.println(reader.readLine());
    }

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("hello-world.sh"))) {
      writer.write("puts 'Hello world'");
    }

    try (BufferedReader reader = Files.newBufferedReader(path)) {
      long countPuts = reader.lines().filter(line -> line.contains("put")).count();
      System.out.println(countPuts);
    }
  }
Exemple #17
0
 /**
  * Creates file blah: 0000 0001 0002 0003 . . . 3999
  *
  * <p>Blah extends beyond a single page of memory so that the ability to index into a file of
  * multiple pages is tested.
  */
 private static void initTestFile(File blah) throws Exception {
   try (BufferedWriter writer = Files.newBufferedWriter(blah.toPath(), ISO_8859_1)) {
     for (int i = 0; i < 4000; i++) {
       String number = new Integer(i).toString();
       for (int h = 0; h < 4 - number.length(); h++) writer.write("0");
       writer.write("" + i);
       writer.newLine();
     }
   }
 }
Exemple #18
0
 @Override
 public CharSink createSink() throws IOException {
   Path file = createFile();
   if (initialString != null) {
     try (Writer writer = java.nio.file.Files.newBufferedWriter(file, Charsets.UTF_8)) {
       writer.write(initialString);
     }
     return MoreFiles.asCharSink(file, Charsets.UTF_8, StandardOpenOption.APPEND);
   }
   return MoreFiles.asCharSink(file, Charsets.UTF_8);
 }
 private void createTmpFile(Path filePath, String content, String exceptionPrefix) {
   try (BufferedWriter out = Files.newBufferedWriter(filePath, Charset.defaultCharset())) {
     Set<PosixFilePermission> permissions = new HashSet<>();
     permissions.add(PosixFilePermission.OWNER_READ);
     permissions.add(PosixFilePermission.OWNER_WRITE);
     Files.setPosixFilePermissions(filePath, permissions);
     out.write(content);
   } catch (Exception e) {
     throw SyssvcException.syssvcExceptions.localRepoError(exceptionPrefix + e);
   }
 }
Exemple #20
0
 /** Write string containing all movie records to a file - overwrite the whole file. */
 private void writeStringToFile(String aFileContents) {
   Path moviesPath = Paths.get(getMovieFileName());
   fLogger.fine("Writing movies to: " + moviesPath);
   try (BufferedWriter writer = Files.newBufferedWriter(moviesPath, ENCODING)) {
     writer.write(aFileContents);
   } catch (FileNotFoundException ex) {
     fLogger.severe("Cannot find movies text file.");
   } catch (IOException ex) {
     fLogger.severe("Problem while saving movies text file.");
   }
 }
Exemple #21
0
 public static synchronized void saveHeaders(Path path, ArrayList<String> headers) {
   try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
     for (String line : headers) {
       writer.write(line);
       writer.newLine();
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 /**
  * Writes out the content of a string payload into a file using given charset. The file will be
  * overwritten if exists and parent directories will be created if needed.
  */
 public static void writeFile(final Path file, final Charset charset, final String payload)
     throws IOException {
   checkNotNull(file);
   checkNotNull(charset);
   checkNotNull(payload);
   DirSupport.mkdir(file.getParent());
   try (final BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
     writer.write(payload);
     writer.flush();
   }
 }
Exemple #23
0
 static void writeAsBase64ToFile(Path filename, int numKeys, int numValuesPerKeys)
     throws IOException {
   BufferedWriter bw = Files.newBufferedWriter(filename, Charset.defaultCharset());
   for (int i = 0; i < numKeys; ++i) {
     bw.write(DatatypeConverter.printBase64Binary(makeKey(i)));
     for (int j = 0; j < numValuesPerKeys; ++j) {
       bw.append(' ').write(DatatypeConverter.printBase64Binary(makeValue(j)));
     }
     bw.newLine();
   }
   bw.close();
 }
 /**
  * @param key The best key for the
  * @param path
  */
 private void decryptFile(int key, String path) {
   try (BufferedReader br = Files.newBufferedReader(Paths.get(path));
       BufferedWriter bw = Files.newBufferedWriter(Paths.get(path + ".dec"))) {
     RailFence rf = new RailFence();
     String line;
     while ((line = br.readLine()) != null) {
       bw.write(rf.decrypt(line, key) + "\n");
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemple #25
0
 private static void storeAccessToken(long useId, AccessToken accessToken) {
   try (BufferedWriter writer =
       Files.newBufferedWriter(Paths.get("token.txt"), Charset.forName("UTF-8"))) {
     writer.append(accessToken.getToken());
     writer.append("\n");
     writer.append(accessToken.getTokenSecret());
     writer.append("\n");
     writer.append(accessToken.getUserId() + "");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 public static void writeHelperFunction() throws IOException {
   try (BufferedWriter out =
       Files.newBufferedWriter(Paths.get("addToPlot.m"), StandardCharsets.UTF_8)) {
     out.write(
         "function handle = addToPlot(numTerms, perDoc, color, linestyle, linewidth)\n"
             + "handle = line(numTerms, perDoc);\n"
             + "set(handle, 'color', color);\n"
             + "set(handle, 'linestyle',linestyle);\n"
             + "set(handle, 'LineWidth',linewidth);\n"
             + "end\n");
   }
 }
  @Override
  public void openFile(String name) {
    filename = name;

    Path path = FileSystems.getDefault().getPath(filename);

    Charset charset = Charset.forName("UTF-8");
    try {
      writer = Files.newBufferedWriter(path, charset);
    } catch (IOException exc) {
      exc.printStackTrace();
    }
  }
Exemple #28
0
 static void populate(Path root, String... args) throws IOException {
   if (!Files.exists(root)) Files.createDirectory(root);
   for (int i = 0; i < args.length; i += 2) {
     String filename = args[i];
     String content = args[i + 1];
     Path p = root.resolve(filename);
     Files.createDirectories(p.getParent());
     try (PrintWriter out =
         new PrintWriter(Files.newBufferedWriter(p, Charset.defaultCharset()))) {
       out.println(content);
     }
   }
 }
 public void writeFile() {
   Path inputFile = Paths.get("input.txt");
   Path outputFile = Paths.get("output.txt");
   try {
     BufferedReader reader = Files.newBufferedReader(inputFile, Charset.defaultCharset());
     BufferedWriter writer = Files.newBufferedWriter(inputFile, Charset.defaultCharset());
     String lineFromFile = "";
     while ((lineFromFile = reader.readLine()) != null) writer.append(lineFromFile);
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  private static PrintWriter argumentToOutput(String arg, Charset outputCharset)
      throws ParseException, IOException {
    if ("-".equals(arg)) {
      return new PrintWriter(new OutputStreamWriter(System.out, outputCharset));
    }

    final File outFile = new File(arg);
    try {
      return new PrintWriter(Files.newBufferedWriter(outFile.toPath(), outputCharset));
    } catch (FileNotFoundException e) {
      throw new ParseException("Output file '" + outFile + "' not found");
    }
  }