Java Code Examples for com.intellij.openapi.util.io.FileUtil#copy()

The following examples show how to use com.intellij.openapi.util.io.FileUtil#copy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZipUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void extractEntry(ZipEntry entry, final InputStream inputStream, File outputDir, boolean overwrite) throws IOException {
  final boolean isDirectory = entry.isDirectory();
  final String relativeName = entry.getName();
  final File file = new File(outputDir, relativeName);
  file.setLastModified(entry.getTime());
  if (file.exists() && !overwrite) return;

  FileUtil.createParentDirs(file);
  if (isDirectory) {
    file.mkdir();
  }
  else {
    final BufferedInputStream is = new BufferedInputStream(inputStream);
    final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    try {
      FileUtil.copy(is, os);
    }
    finally {
      os.close();
      is.close();
    }
  }
}
 
Example 2
Source File: ClassesExportAction.java    From patcher with Apache License 2.0 6 votes vote down vote up
private void getVirtualFile(String sourceName, VirtualFile virtualFile[], String compileRoot)
        throws Exception {
    if (!ArrayUtils.isEmpty(virtualFile)) {
        VirtualFile arr$[] = virtualFile;
        int len$ = arr$.length;
        for (int i$ = 0; i$ < len$; i$++) {
            VirtualFile vf = arr$[i$];
            String srcName;
            if (StringUtils.indexOf(vf.toString(), "$") != -1)
                srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.indexOf(vf.toString(), "$"));
            else
                srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.length(vf.toString()) - 6);
            String dstName = StringUtils.substring(sourceName, 0, StringUtils.length(sourceName) - 5);
            if (StringUtils.equals(srcName, dstName)) {
                String outRoot = (new StringBuilder()).append(StringUtils.substring(compileRoot, 0, StringUtils.lastIndexOf(compileRoot, "/"))).append("/out").toString();
                String packagePath = StringUtils.substring(vf.getPath(), StringUtils.length(compileRoot), StringUtils.length(vf.getPath()));
                File s = new File(vf.getPath());
                File t = new File((new StringBuilder()).append(outRoot).append(packagePath).toString());
                FileUtil.copy(s, t);
            }
            if (!ArrayUtils.isEmpty(virtualFile))
                getVirtualFile(sourceName, vf.getChildren(), compileRoot);
        }

    }
}
 
Example 3
Source File: SafeFileOutputStream.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void restoreFromBackup(@Nullable Path backup, IOException e) throws IOException {
  if (backup == null) {
    throw new IOException(CommonBundle.message("safe.write.junk", myTarget), e);
  }

  boolean restored = true;
  try (InputStream in = Files.newInputStream(backup, BACKUP_READ); OutputStream out = Files.newOutputStream(myTarget, MAIN_WRITE)) {
    FileUtil.copy(in, out);
  }
  catch (IOException ex) {
    restored = false;
    e.addSuppressed(ex);
  }
  if (restored) {
    throw new IOException(CommonBundle.message("safe.write.restored", myTarget), e);
  }
  else {
    throw new IOException(CommonBundle.message("safe.write.junk.backup", myTarget, backup.getFileName()), e);
  }
}
 
Example 4
Source File: DecompileAndAttachAction.java    From decompile-and-attach with MIT License 6 votes vote down vote up
private static void addFileEntry(ZipOutputStream jarOS, String relativePath, Set<String> writtenPaths,
        CharSequence decompiled) throws IOException {
    if (!writtenPaths.add(relativePath))
        return;

    ByteArrayInputStream fileIS = new ByteArrayInputStream(decompiled.toString().getBytes(Charsets.toCharset("UTF-8")));
    long size = decompiled.length();
    ZipEntry e = new ZipEntry(relativePath);
    if (size == 0) {
        e.setMethod(ZipEntry.STORED);
        e.setSize(0);
        e.setCrc(0);
    }
    jarOS.putNextEntry(e);
    try {
        FileUtil.copy(fileIS, jarOS);
    } finally {
        fileIS.close();
    }
    jarOS.closeEntry();
}
 
Example 5
Source File: JarHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private File copyToMirror(@Nonnull File original, @Nonnull File mirror) {
  ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
  if (progress != null) {
    progress.pushState();
    progress.setText(VfsBundle.message("jar.copy.progress", original.getPath()));
    progress.setFraction(0);
  }

  try {
    FileUtil.copy(original, mirror);
  }
  catch (final IOException e) {
    reportIOErrorWithJars(original, mirror, e);
    return original;
  }
  finally {
    if (progress != null) {
      progress.popState();
    }
  }


  return mirror;
}
 
Example 6
Source File: ArchiveVfsUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void extractEntry(ArchiveEntry entry, final InputStream inputStream, File outputDir, boolean overwrite) throws IOException {
  final boolean isDirectory = entry.isDirectory();
  final String relativeName = entry.getName();
  final File file = new File(outputDir, relativeName);
  if (file.exists() && !overwrite) return;

  FileUtil.createParentDirs(file);
  if (isDirectory) {
    file.mkdir();
  }
  else {
    final BufferedInputStream is = new BufferedInputStream(inputStream);
    final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    try {
      FileUtil.copy(is, os);
    }
    finally {
      os.close();
      is.close();
    }
  }
}
 
Example 7
Source File: ArtifactsCompilerInstance.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void extractFile(VirtualFile sourceFile, File toFile, Set<String> writtenPaths, FileFilter fileFilter) throws IOException {
  if (!writtenPaths.add(toFile.getPath())) {
    return;
  }

  if (!FileUtil.createParentDirs(toFile)) {
    myContext.addMessage(CompilerMessageCategory.ERROR, "Cannot create directory for '" + toFile.getAbsolutePath() + "' file", null, -1, -1);
    return;
  }

  InputStream input = ArtifactCompilerUtil.getArchiveEntryInputStream(sourceFile, myContext).getFirst();
  if (input == null) return;
  final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(toFile));
  try {
    FileUtil.copy(input, output);
  }
  finally {
    input.close();
    output.close();
  }
}
 
Example 8
Source File: PackageFileWorker.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void copyFile(String outputPath, List<CompositePackagingElement<?>> parents) throws IOException {
  if (parents.isEmpty()) {
    final String fullOutputPath = DeploymentUtil.appendToPath(outputPath, myRelativeOutputPath);
    File target = new File(fullOutputPath);
    if (FileUtil.filesEqual(myFile, target)) {
      LOG.debug("  skipping copying file to itself");
    }
    else {
      LOG.debug("  copying to " + fullOutputPath);
      FileUtil.copy(myFile, target);
    }
    return;
  }

  final CompositePackagingElement<?> element = parents.get(0);
  final String nextOutputPath = outputPath + "/" + element.getName();
  final List<CompositePackagingElement<?>> parentsTrail = parents.subList(1, parents.size());
  if (element instanceof ArchivePackagingElement) {
    packFile(nextOutputPath, "", parentsTrail);
  }
  else {
    copyFile(nextOutputPath, parentsTrail);
  }
}
 
Example 9
Source File: ImageUtilsTest.java    From markdown-image-kit with MIT License 5 votes vote down vote up
@Test
public void fileCopyTest() throws IOException {
    File file1 = new File("/Users/dong4j/Downloads/xu.png");
    File file2 = new File("/Users/dong4j/Downloads/xu1.png");
    FileUtils.copyToFile(new FileInputStream(file1), file2);
    FileUtil.copy(new FileInputStream(file1), new FileOutputStream(file2));
}
 
Example 10
Source File: VirtualFileDiffElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public VirtualFileDiffElement copyTo(DiffElement<VirtualFile> container, String relativePath) {
  try {
    final File src = new File(myFile.getPath());
    final File trg = new File(container.getValue().getPath() + relativePath + src.getName());
    FileUtil.copy(src, trg);
    final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(trg);
    if (virtualFile != null) {
      return new VirtualFileDiffElement(virtualFile);
    }
  }
  catch (IOException e) {//
  }
  return null;
}
 
Example 11
Source File: Executor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void cp(String fileName, File destinationDir) {
  try {
    FileUtil.copy(child(fileName), new File(destinationDir, fileName));
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 12
Source File: ZipArchivePackagingElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addFile(@Nonnull ZipOutputStream zipOutputStream, @Nonnull InputStream stream, @Nonnull String relativePath, long fileLength, long lastModified) throws IOException {
  ZipEntry e = new ZipEntry(relativePath);
  e.setTime(lastModified);
  e.setSize(fileLength);

  zipOutputStream.putNextEntry(e);
  FileUtil.copy(stream, zipOutputStream);
  zipOutputStream.closeEntry();
}
 
Example 13
Source File: TemplateUtils.java    From CppTools with Apache License 2.0 5 votes vote down vote up
public static void createOrResetFileContent(VirtualFile sourcePathDir, String fileName, StringBufferInputStream inputStream) throws IOException {
  VirtualFile child = sourcePathDir.findChild(fileName);
  if (child == null) child = sourcePathDir.createChildData(CppModuleBuilder.class, fileName);
  OutputStream outputStream = child.getOutputStream(CppModuleBuilder.class);

  FileUtil.copy(inputStream, outputStream);
  outputStream.flush();
  outputStream.close();
}
 
Example 14
Source File: PantsUtil.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException {
  final File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY);
  for (File child : children) {
    final File target = new File(toDir, child.getName());
    if (child.isFile()) {
      FileUtil.copy(child, target);
    }
    else {
      FileUtil.copyDir(child, target, false);
    }
  }
}
 
Example 15
Source File: PantsIntegrationTestCase.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
protected void cleanProjectRoot() throws ExecutionException, IOException {
  final File projectDir = new File(myProjectRoot.getPath());
  assertTrue(projectDir.exists());
  if (readOnly) {
    final File originalIni = new File(projectDir, "pants.ini");
    final File originalIniCopy = new File(projectDir, "pants.ini.copy");
    if (originalIniCopy.exists()) {
      FileUtil.copy(originalIniCopy, originalIni);
    }
    // work around copyDirContent's copying of symlinks as hard links causing pants to fail
    assertTrue("Failed to clean up!", FileUtil.delete(new File(projectDir, ".pants.d")));
    // and IJ data
    assertTrue("Failed to clean up!", FileUtil.delete(new File(projectDir, ".idea")));
    for (File file : getProjectFoldersToCopy()) {
      final File[] children = file.listFiles();
      if (children == null) {
        continue;
      }
      for (File child : children) {
        final File copiedChild = new File(projectDir, child.getName());
        if (copiedChild.exists()) {
          assertTrue("Failed to clean up!", FileUtil.delete(copiedChild));
        }
      }
    }
  }
  else {
    cmd("git", "reset", "--hard");
    cmd("git", "clean", "-fdx");
  }
}
 
Example 16
Source File: ShelveChangesManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private ShelvedChangeList createRecycledChangelist(ShelvedChangeList changeList) throws IOException {
  final File newPatchDir = generateUniqueSchemePatchDir(changeList.DESCRIPTION, true);
  final File newPath = getPatchFileInConfigDir(newPatchDir);
  FileUtil.copy(new File(changeList.PATH), newPath);
  final ShelvedChangeList listCopy = new ShelvedChangeList(newPath.getAbsolutePath(), changeList.DESCRIPTION, new ArrayList<>(changeList.getBinaryFiles()));
  listCopy.markToDelete(changeList.isMarkedToDelete());
  listCopy.setName(newPatchDir.getName());
  return listCopy;
}
 
Example 17
Source File: DecompileAndAttachAction.java    From decompile-and-attach with MIT License 5 votes vote down vote up
private File copy(Project project, String baseDirPath, VirtualFile sourceVF, File tmpJarFile, String filename)
        throws IOException {
    String libraryName = filename.replace(".jar", "-sources.jar");
    String fullPath = baseDirPath + File.separator + libraryName;
    File result = new File(fullPath);
    if (result.exists()) {
        FileUtil.deleteWithRenaming(result);
        result = new File(fullPath);
        result.createNewFile();
    }
    FileUtil.copy(tmpJarFile, result);
    return result;
}
 
Example 18
Source File: WeiboOssClient.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * Upload string.
 *
 * @param ossClient   the oss client
 * @param inputStream the input stream
 * @param fileName    the file name
 * @return the string
 * @throws IOException the io exception
 */
public String upload(WbpUploadRequest ossClient, InputStream inputStream, String fileName) {
    File file = ImageUtils.buildTempFile(fileName);
    try {
        FileUtil.copy(inputStream, new FileOutputStream(file));
        return upload(ossClient, file);
    } catch (IOException e) {
        log.trace("", e);
    }
    return "";
}
 
Example 19
Source File: DeploymentUtilImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void copyFile(@Nonnull final File fromFile,
                     @Nonnull final File toFile,
                     @Nonnull CompileContext context,
                     @Nullable Set<String> writtenPaths,
                     @Nullable FileFilter fileFilter) throws IOException {
  if (fileFilter != null && !fileFilter.accept(fromFile)) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Skipping " + fromFile.getAbsolutePath() + ": it wasn't accepted by filter " + fileFilter);
    }
    return;
  }
  checkPathDoNotNavigatesUpFromFile(fromFile);
  checkPathDoNotNavigatesUpFromFile(toFile);
  if (fromFile.isDirectory()) {
    final File[] fromFiles = fromFile.listFiles();
    toFile.mkdirs();
    for (File file : fromFiles) {
      copyFile(file, new File(toFile, file.getName()), context, writtenPaths, fileFilter);
    }
    return;
  }
  if (toFile.isDirectory()) {
    context.addMessage(CompilerMessageCategory.ERROR,
                       CompilerBundle.message("message.text.destination.is.directory", createCopyErrorMessage(fromFile, toFile)), null, -1, -1);
    return;
  }
  if (FileUtil.filesEqual(fromFile, toFile) || writtenPaths != null && !writtenPaths.add(toFile.getPath())) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Skipping " + fromFile.getAbsolutePath() + ": " + toFile.getAbsolutePath() + " is already written");
    }
    return;
  }
  if (!FileUtil.isFilePathAcceptable(toFile, fileFilter)) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Skipping " + fromFile.getAbsolutePath() + ": " + toFile.getAbsolutePath() + " wasn't accepted by filter " + fileFilter);
    }
    return;
  }
  context.getProgressIndicator().setText("Copying files");
  context.getProgressIndicator().setText2(fromFile.getPath());
  try {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Copy file '" + fromFile + "' to '"+toFile+"'");
    }
    if (toFile.exists() && !SystemInfo.isFileSystemCaseSensitive) {
      File canonicalFile = toFile.getCanonicalFile();
      if (!canonicalFile.getAbsolutePath().equals(toFile.getAbsolutePath())) {
        FileUtil.delete(toFile);
      }
    }
    FileUtil.copy(fromFile, toFile);
  }
  catch (IOException e) {
    context.addMessage(CompilerMessageCategory.ERROR, createCopyErrorMessage(fromFile, toFile) + ": "+ ExceptionUtil.getThrowableText(e), null, -1, -1);
  }
}
 
Example 20
Source File: ZipUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean addFileToZip(@Nonnull ZipOutputStream zos,
                                   @Nonnull File file,
                                   @Nonnull String relativeName,
                                   @Nullable Set<String> writtenItemRelativePaths,
                                   @Nullable FileFilter fileFilter,
                                   @Nonnull FileContentProcessor contentProcessor) throws IOException {
  while (relativeName.length() != 0 && relativeName.charAt(0) == '/') {
    relativeName = relativeName.substring(1);
  }

  boolean isDir = file.isDirectory();
  if (isDir && !StringUtil.endsWithChar(relativeName, '/')) {
    relativeName += "/";
  }
  if (fileFilter != null && !FileUtil.isFilePathAcceptable(file, fileFilter)) return false;
  if (writtenItemRelativePaths != null && !writtenItemRelativePaths.add(relativeName)) return false;

  if (LOG.isDebugEnabled()) {
    LOG.debug("Add " + file + " as " + relativeName);
  }

  long size = isDir ? 0 : file.length();
  ZipEntry e = new ZipEntry(relativeName);
  e.setTime(file.lastModified());
  if (size == 0) {
    e.setMethod(ZipEntry.STORED);
    e.setSize(0);
    e.setCrc(0);
  }
  zos.putNextEntry(e);
  if (!isDir) {
    InputStream is = null;
    try {
      is = contentProcessor.getContent(file);
      FileUtil.copy(is, zos);
    }
    finally {
      StreamUtil.closeStream(is);
    }
  }
  zos.closeEntry();
  return true;
}