コード例 #1
0
  public static void main(String[] args) throws IOException {
    Closer closer = Closer.create();
    // copy a file
    File origin = new File("join_temp");
    File copy = new File("target_temp");

    try {
      BufferedReader reader = new BufferedReader(new FileReader("join_temp"));
      BufferedWriter writer = new BufferedWriter(new FileWriter("target_temp"));

      closer.register(reader);
      closer.register(writer);

      String line;

      while ((line = reader.readLine()) != null) {
        writer.write(line);
      }
    } catch (IOException e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }

    Files.copy(origin, copy);

    File moved = new File("moved");

    // moving renaming
    Files.move(copy, moved);

    // working files as string
    List<String> lines = Files.readLines(origin, Charsets.UTF_8);

    HashCode hashCode = Files.hash(origin, Hashing.md5());
    System.out.println(hashCode);

    // file write and append
    String hamlet = "To be, or not to be it is a question\n";
    File write_and_append = new File("write_and_append");

    Files.write(hamlet, write_and_append, Charsets.UTF_8);

    Files.append(hamlet, write_and_append, Charsets.UTF_8);

    //        write_and_append.deleteOnExit();

    Files.write("OverWrite the file", write_and_append, Charsets.UTF_8);

    // ByteSource ByteSink
    ByteSource fileBytes = Files.asByteSource(write_and_append);
    byte[] readBytes = fileBytes.read();
    // equals to pre line -> Files.toByteArray(write_and_append) == readBytes

    ByteSink fileByteSink = Files.asByteSink(write_and_append);
    fileByteSink.write(Files.toByteArray(write_and_append));

    BaseEncoding base64 = BaseEncoding.base64();
    System.out.println(base64.encode("123456".getBytes()));
  }
コード例 #2
0
ファイル: JavaNewIO.java プロジェクト: juniuszhou/java
  public static void main(String args[]) {
    try {
      aServer asr = new aServer();

      // file channel.
      FileInputStream is = new FileInputStream("");
      is.read();
      FileChannel cha = is.getChannel();
      ByteBuffer bf = ByteBuffer.allocate(1024);
      bf.flip();

      cha.read(bf);

      // Path Paths
      Path pth = Paths.get("", "");

      // Files some static operation.
      Files.newByteChannel(pth);
      Files.copy(pth, pth);
      // file attribute, other different class for dos and posix system.
      BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class);
      bas.size();

    } catch (Exception e) {
      System.err.println(e);
    }

    System.out.println("hello ");
  }
コード例 #3
0
 /** Puts library to temp dir and loads to memory */
 private static void loadLib(String name) {
   Path sourcePath = Paths.get(LIBPATH, name);
   try {
     Path libPath = Files.copy(sourcePath, tempPath, StandardCopyOption.REPLACE_EXISTING);
     System.load(libPath.toString());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #4
0
ファイル: Main.java プロジェクト: punki/VirtualnyFS
 public static void main(String[] args) throws IOException {
   Path jarfile = Paths.get("/home/punki/test.zip");
   FileSystem fs = FileSystems.newFileSystem(jarfile, null);
   Path path = fs.getPath("tekst.txt");
   System.out.println("path.toString() = " + path.toString());
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   Files.copy(path, outputStream);
   System.out.println("bytes = " + new String(outputStream.toByteArray()));
   List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
   for (String line : lines) {
     System.out.println("line = " + line);
   }
 }
コード例 #5
0
  public static void createHierarchy(
      ArrayList<Map<String, String>> data, String source, String destOriginal) {
    cycle = 0;
    for (Map<String, String> map : data) {
      String dest = destOriginal + "\\" + "Cycle" + cycle;
      File dir = new File(dest);
      if (!dir.exists()) {
        dir.mkdir();
      }
      for (Map.Entry<String, String> entry : map.entrySet()) {

        String dirName = entry.getKey().replaceAll(":", "_");
        File sourceDir = new File(source);
        File subDir = new File(dest + "\\" + dirName);
        if (!subDir.exists()) {
          subDir.mkdir();
        }
        String[] hitValTokens = entry.getValue().split(",");
        for (final String hitVal : hitValTokens) {
          File[] matchingFiles =
              sourceDir.listFiles(
                  new FilenameFilter() {

                    @Override
                    public boolean accept(File dir, String name) {
                      return name.equals(hitVal + ".jpg");
                    }
                  });

          if (matchingFiles != null && matchingFiles.length > 0) {
            try {
              Path FROM = Paths.get(source + "\\" + hitVal + ".jpg");
              Path TO = Paths.get(dest + "\\" + dirName + "\\" + hitVal + ".jpg");
              // overwrite existing file, if exists
              CopyOption[] options =
                  new CopyOption[] {
                    StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES
                  };
              Files.copy(FROM, TO, options);
            } catch (IOException ex) {
              Logger.getLogger(FolderHeirarchyGenerator.class.getName())
                  .log(Level.SEVERE, null, ex);
            }
          }
        }
      }
      cycle++;
    }
  }
コード例 #6
0
ファイル: CudaEngine.java プロジェクト: TsubameDono/TurtleKit
 private static void extractAndLoadNativeLib(String nativeLibName, Path target) {
   //		System.err.println("loading "+nativeLibName);
   final Path path = Paths.get(target.toString(), nativeLibName);
   if (!path.toFile().exists()) {
     try (InputStream is =
         CudaEngine.class
             .getClassLoader()
             .getResourceAsStream("/lib/" + nativeLibName)) { // TODO TK property for lib dir
       Files.copy(is, path);
     } catch (IOException e) {
       e.printStackTrace();
     } catch (NullPointerException e) { // TODO find a way to do it instead of eclipse
       final Path eclipsePath = FileSystems.getDefault().getPath("lib", nativeLibName);
       try {
         Files.copy(eclipsePath, path);
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   }
   System.load(path.toString());
   //		System.load(nativeLibName);
 }
コード例 #7
0
ファイル: CudaEngine.java プロジェクト: TsubameDono/TurtleKit
 // void compileKernelsPtx()
 static void compileKernelsPtx() throws IOException {
   if (!new File(ioTmpDir, PHEROMONES_CU + ".ptx").exists()) { // TODO externalize
     try (InputStream is =
         CudaEngine.class.getResourceAsStream(
             "/turtlekit/cuda/kernels/" + PHEROMONES_CU + ".cu")) {
       final Path path = Paths.get(ioTmpDir, PHEROMONES_CU + ".cu");
       try {
         Files.copy(is, path);
       } catch (FileAlreadyExistsException e) {
       }
       System.err.println("--------------- Compiling ptx ----------------------");
       KernelLauncher.create(
           path.toString(),
           Kernel.DIFFUSION_TO_TMP.name(),
           false,
           "--use_fast_math",
           "--prec-div=false"); // ,"--gpu-architecture=sm_20");
     } catch (IOException e) {
       throw e;
     }
   }
 }
コード例 #8
0
  public void downloadFlat(String artifact, String copyToDir) {
    OutputBouble bouble = OutputBouble.push();
    try {
      Artifact theArtifact = new DefaultArtifact(artifact);

      HashSet<Artifact> downloadThese = new HashSet<Artifact>();
      downloadThese.add(theArtifact);
      Stack<Artifact> downloadDependenciesOfThese = new Stack<Artifact>();
      downloadDependenciesOfThese.add(theArtifact);

      while (!downloadDependenciesOfThese.isEmpty()) {
        Artifact getDependenciesOfThis = downloadDependenciesOfThese.pop();
        List<Artifact> dependencies =
            dependencyManager.getDirectDependencies(getDependenciesOfThis);
        for (Artifact a : dependencies) {
          if (!downloadThese.contains(a)) {
            downloadThese.add(a);
            downloadDependenciesOfThese.add(a);
          }
        }
      }

      File destination = new File(copyToDir);
      destination.mkdirs();

      for (Artifact a : downloadThese) {
        File theFile = getAsFile(a);
        Files.copy(theFile.toPath(), new File(destination, theFile.getName()).toPath());
      }
    } catch (Exception e) {
      OutputBouble.reportError(e);
    } finally {
      bouble.pop();
      if (bouble.isError) bouble.writeToParent();
    }
  }
コード例 #9
0
 @Override
 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
   Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption);
   return FileVisitResult.CONTINUE;
 }
コード例 #10
0
ファイル: CopyWindow.java プロジェクト: schneehund/synchros
    public void cnpStart(Path quellOrdner, Path zielOrdner) {
      try {
        DirectoryStream<Path> qstream = Files.newDirectoryStream(quellOrdner);
        for (Path qfile : qstream) {
          Path target = Paths.get(zielOrdner.toString() + "/" + qfile.getFileName());
          if (abbruch) break;
          if (Files.isDirectory(qfile) && !Files.exists(target)) {
            Files.createDirectory(target);
            textArea.append("Verzeichnis: " + qfile + " wurde erstellt" + System.lineSeparator());
            cnpStart(
                Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()),
                Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()));
          } else if (Files.isDirectory(qfile) && Files.exists(target)) {
            textArea.append("Wechsle in Verzeichnis: " + qfile + System.lineSeparator());
            cnpStart(
                Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()),
                Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()));
          }
          // Wenn die Datei noch nicht existiert
          else if (!Files.exists(target)) {
            textArea.append(
                "Datei " + target.toString() + " wurde erstellt" + System.lineSeparator());
            Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING);

          }
          // Wenn Datei im Zielverzeichnis schon existiert
          else if (Files.exists(target)) {
            if (cAUeSchr) {
              textArea.append(
                  "Datei "
                      + target.toString()
                      + " wird absolut überschrieben"
                      + System.lineSeparator());
              Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING);
            } else if (cUeSchr) {
              if (checkAlter(
                  Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()),
                  Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()))) {
                textArea.append(
                    target.toString()
                        + " wird mit neuer Datei überschrieben"
                        + System.lineSeparator());
                Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING);
              } else {
                textArea.append(
                    target.toString() + " alte Datei bleibt bestehen" + System.lineSeparator());
              }
            } else
              textArea.append(
                  target.toString() + " alte Datei bleibt bestehen" + System.lineSeparator());
          }
          pbCounter++;
          progressBar.setValue(pbCounter);
        }

        qstream.close();
      } catch (IOException e) {

        e.printStackTrace();
      }
    }