java.nio.file.StandardCopyOption Java Examples

The following examples show how to use java.nio.file.StandardCopyOption. 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: FileSystemStorageService.java    From code-examples with MIT License 6 votes vote down vote up
@Override
public String store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, this.rootLocation.resolve(filename),
                    StandardCopyOption.REPLACE_EXISTING);
        }
    }
    catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }

    return filename;
}
 
Example #2
Source File: ConfigUpdaterTest.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
@BeforeAll
static void prepareConfigFiles() throws URISyntaxException, IOException {
    oldConfig = tempDir.resolve("config.yml").toFile();
    File configResource = TestResources.getTestResourceFile("config/4.5.2-config.yml", ConfigUpdater.class);
    Files.copy(configResource.toPath(), oldConfig.toPath(), StandardCopyOption.REPLACE_EXISTING);

    oldBungeeConfig = tempDir.resolve("bungeeconfig.yml").toFile();
    File bungeeConfigResource = TestResources.getTestResourceFile("config/4.5.2-bungeeconfig.yml", ConfigUpdater.class);
    Files.copy(bungeeConfigResource.toPath(), oldBungeeConfig.toPath(), StandardCopyOption.REPLACE_EXISTING);

    newConfig = tempDir.resolve("newconfig.yml");
    TestResources.copyResourceIntoFile(newConfig.toFile(), "/assets/plan/config.yml");

    newBungeeConfig = tempDir.resolve("newbungeeconfig.yml");
    TestResources.copyResourceIntoFile(newBungeeConfig.toFile(), "/assets/plan/bungeeconfig.yml");

    PluginLogger testLogger = new TestPluginLogger();
    errorLogger = Mockito.mock(ErrorLogger.class);
    UNDER_TEST = new ConfigUpdater(testLogger, errorLogger);
}
 
Example #3
Source File: FileSystemStorageServiceImpl.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
public void store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                "Cannot store file with relative path outside current directory " + filename);
        }
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }
}
 
Example #4
Source File: ClassFileInstaller.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param args The names of the classes to dump
 * @throws Exception
 */
public static void main(String... args) throws Exception {
    for (String arg : args) {
        ClassLoader cl = ClassFileInstaller.class.getClassLoader();

        // Convert dotted class name to a path to a class file
        String pathName = arg.replace('.', '/').concat(".class");
        InputStream is = cl.getResourceAsStream(pathName);

        // Create the class file's package directory
        Path p = Paths.get(pathName);
        if (pathName.contains("/")) {
            Files.createDirectories(p.getParent());
        }
        // Create the class file
        Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
    }
}
 
Example #5
Source File: CheckTaskTests.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
private void copyFolder(Path source, Path target) throws IOException {
	try (Stream<Path> stream = Files.walk(source)) {
		stream.forEach((child) -> {
			try {
				Path relative = source.relativize(child);
				Path destination = target.resolve(relative);
				if (!destination.toFile().isDirectory()) {
					Files.copy(child, destination, StandardCopyOption.REPLACE_EXISTING);
				}
			}
			catch (Exception ex) {
				throw new IllegalStateException(ex);
			}
		});
	}
}
 
Example #6
Source File: ReplayCacheTestProc.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static Ex round(int i, int old, int server, boolean expected)
        throws Exception {
    ps[server].println("TEST");
    ps[server].println(reqs.get(old).msg);
    String reply = ps[server].readData();
    Ex result = new Ex();
    result.i = i;
    result.expected = expected;
    result.server = ps[server].debug();
    result.actual = Boolean.valueOf(reply);
    result.user = reqs.get(old).user;
    result.peer = reqs.get(old).peer;
    result.old = old;
    result.csize = csize(result.peer);
    result.hash = hash(reqs.get(old).msg);
    if (new File(dfl(result.peer)).exists()) {
        Files.copy(Paths.get(dfl(result.peer)), Paths.get(
            String.format("%03d-USER%d-host%d-%s-%s",
                i, result.user, result.peer, result.server,
                result.actual)
            + "-" + result.hash),
            StandardCopyOption.COPY_ATTRIBUTES);
    }
    return result;
}
 
Example #7
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public void add( String filepattern ) {
  try {
    if ( filepattern.endsWith( ".ours" ) || filepattern.endsWith( ".theirs" ) ) {
      FileUtils.rename( new File( directory, filepattern ),
          new File( directory, FilenameUtils.removeExtension( filepattern ) ),
          StandardCopyOption.REPLACE_EXISTING );
      filepattern = FilenameUtils.removeExtension( filepattern );
      org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, filepattern + ".ours" ) );
      org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, filepattern + ".theirs" ) );
    }
    git.add().addFilepattern( filepattern ).call();
  } catch ( Exception e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
}
 
Example #8
Source File: Util.java    From ecosys with Apache License 2.0 6 votes vote down vote up
public static File getClientLogFile(String file, String username, String serverip,
    boolean rotate) throws IOException {
  if (Util.LOG_DIR == null) {
    throw new IOException("LogDir is null");
  }

  String filename = Util.LOG_DIR + "/" + file + ".";
  filename += Math.abs((username + "." + serverip).hashCode()) % 1000000;
  File f = new File(filename);
  if (!f.getParentFile().isDirectory()) {
    f.getParentFile().mkdirs();
  }

  if (!f.exists()) {
    //create file if it does not exist
    f.createNewFile();
  } else if (rotate && f.length() > Constant.LogRotateSize) {
    // rotate log file when file is large than 500M
    long current = System.currentTimeMillis();
    // copy the log to a new file with timestamp
    String LogCopy = filename + "." + current / 1000;
    Files.move(f.toPath(), Paths.get(LogCopy), StandardCopyOption.REPLACE_EXISTING);
  }

  return f;
}
 
Example #9
Source File: ResourcePackBuilder.java    From I18nUpdateMod with MIT License 6 votes vote down vote up
private void copyResourcePack() {
    assetFolder.mkdirs();
    // PNG 图标
    File icon = new File(rootPath, "pack.png");
    if (!icon.exists()) {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream in = classLoader.getResourceAsStream("assets/i18nmod/icon/pack.png");

        try {
            Files.copy(in, icon.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            logger.error("Error while copying icon file:", e);
        }
    }
    // pack.mcmeta
    writePackMeta();
}
 
Example #10
Source File: BackupService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static void updateApplicationDb(@Nullable Db restoreDb, File path) {
   try {
      File appDbPath = DbService.getApplicationDbPath();

      Path updatedDbPath = FileSystems.getDefault().getPath(path.getAbsolutePath());
      Path existingDbPath = FileSystems.getDefault().getPath(appDbPath.getAbsolutePath());

      Files.move(updatedDbPath, existingDbPath, StandardCopyOption.REPLACE_EXISTING);

      if (restoreDb != null) {
         restoreDb.close();
      }

      DbService.reloadApplicationDb();
   } catch (IOException ex) {
      log.warn("could not overwrite application database with backup copy:", ex);
      throw new RuntimeException(ex);
   }
}
 
Example #11
Source File: ProcessAttachDebuggee.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
Example #12
Source File: OperationUtil.java    From lrkFM with MIT License 6 votes vote down vote up
private static boolean doCopyNoValidation(FMFile f, File d) throws BlockingStuffOnMainThreadException {
    if(Looper.myLooper() == Looper.getMainLooper()) {
        throw new BlockingStuffOnMainThreadException();
    }
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Files.copy(f.getFile().toPath(), d.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } else {
            if (f.getFile().isDirectory()) {
                copyDirectory(f.getFile(), d);
            } else {
                copyFile(f.getFile(), d);
            }
        }
        return true;
    } catch (IOException e) {
        Log.e(TAG, "Unable to copy file!", e);
        return false;
    }
}
 
Example #13
Source File: ReplayCacheTestProc.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Ex round(int i, int old, int server, boolean expected)
        throws Exception {
    ps[server].println("TEST");
    ps[server].println(reqs.get(old).msg);
    String reply = ps[server].readData();
    Ex result = new Ex();
    result.i = i;
    result.expected = expected;
    result.server = ps[server].debug();
    result.actual = Boolean.valueOf(reply);
    result.user = reqs.get(old).user;
    result.peer = reqs.get(old).peer;
    result.old = old;
    result.csize = csize(result.peer);
    result.hash = hash(reqs.get(old).msg);
    if (new File(dfl(result.peer)).exists()) {
        Files.copy(Paths.get(dfl(result.peer)), Paths.get(
            String.format("%03d-USER%d-host%d-%s-%s",
                i, result.user, result.peer, result.server,
                result.actual)
            + "-" + result.hash),
            StandardCopyOption.COPY_ATTRIBUTES);
    }
    return result;
}
 
Example #14
Source File: ProcessAttachDebuggee.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
Example #15
Source File: MCRUploadHandlerIFS.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private InputStream preprocessInputStream(String path, InputStream in, long length, Supplier<Path> tempFileSupplier)
    throws IOException {
    List<MCRPostUploadFileProcessor> activeProcessors = FILE_PROCESSORS.stream().filter(p -> p.isProcessable(path))
        .collect(Collectors.toList());
    if (activeProcessors.isEmpty()) {
        return in;
    }
    Path currentTempFile = tempFileSupplier.get();
    try (InputStream initialIS = in) {
        Files.copy(initialIS, currentTempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    long myLength = Files.size(currentTempFile);
    if (length >= 0 && length != myLength) {
        throw new IOException("Length of transmitted data does not match promised length: " + myLength + "!="
            + length);
    }
    for (MCRPostUploadFileProcessor pufp : activeProcessors) {
        currentTempFile = pufp.processFile(path, currentTempFile, tempFileSupplier);
    }
    return Files.newInputStream(currentTempFile);
}
 
Example #16
Source File: CategorizedQueryCollector.java    From evosql with Apache License 2.0 6 votes vote down vote up
void open() throws IOException {
	outputs = new PrintStream[SYSTEMS];
	String scenarioPath = Paths.get(System.getProperty("user.dir")).toString() + "/scenarios/";
	// For each system, 
	for (int i = 0; i < SYSTEMS; i++) {
		String path = scenarioPath + systemFolders[i] + "-sampled/";
		// rename queries.sql if it exists
		if (Files.exists(Paths.get(path + "queries.sql"))) {
			Files.move(Paths.get(path + "queries.sql")
					, Paths.get(path + "queries-" + timeStampPattern.format(java.time.LocalDateTime.now()) + ".sql")
					, StandardCopyOption.REPLACE_EXISTING);
		}
		
		// Create new queries.sql
		outputs[i] = new PrintStream(path + "queries.sql");
	}
}
 
Example #17
Source File: Ws281xLedStrip.java    From rpi-ws281x-java with Apache License 2.0 6 votes vote down vote up
private static void initializeNative() {
    synchronized ( loaded ) {
        if ( !loaded.get() ) {
            try {
                Path path = Files.createTempFile( "lib" + LIB_NAME, ".so" );
                path.toFile().deleteOnExit();
                Files.copy( Ws281xLedStrip.class.getResourceAsStream( "/lib" + LIB_NAME + ".so" ), path,
                        StandardCopyOption.REPLACE_EXISTING );
                System.load( path.toString() );
                loaded.set( true );
                LOG.info("Native library loaded");
            } catch ( IOException e ) {
                LOG.error( "Error loading library from classpath: ", e );

                // Try load the usual way...
                System.loadLibrary( LIB_NAME );
                loaded.set( true );
                LOG.info("Native library loaded");
            }
        }
    }
}
 
Example #18
Source File: Archives.java    From wildfly-maven-plugin with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Path getArchive(final Path path) throws IOException {
    final Path result;
    // Get the extension
    final String fileName = path.getFileName().toString();
    final String loweredFileName = fileName.toLowerCase(Locale.ENGLISH);
    if (loweredFileName.endsWith(".gz")) {
        String tempFileName = fileName.substring(0, loweredFileName.indexOf(".gz"));
        final int index = tempFileName.lastIndexOf('.');
        if (index > 0) {
            result = Files.createTempFile(tempFileName.substring(0, index), tempFileName.substring(index));
        } else {
            result = Files.createTempFile(tempFileName.substring(0, index), "");
        }
        try (CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream(new BufferedInputStream(Files.newInputStream(path)))) {
            Files.copy(in, result, StandardCopyOption.REPLACE_EXISTING);
        } catch (CompressorException e) {
            throw new IOException(e);
        }
    } else {
        result = path;
    }
    return result;
}
 
Example #19
Source File: ProcessAttachDebuggee.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
Example #20
Source File: Utils.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Provisions a project that's part of the "testProjects"
 * @param folderName the folderName under "testProjects" to provision from
 * @return the provisioned project
 * @throws CoreException
 * @throws IOException
 */
public static IProject provisionTestProject(String folderName) throws CoreException, IOException {
	URL url = FileLocator.find(Platform.getBundle("org.eclipse.wildwebdeveloper.tests"),
			Path.fromPortableString("testProjects/" + folderName), null);
	url = FileLocator.toFileURL(url);
	File folder = new File(url.getFile());
	if (folder.exists()) {
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testProject" + System.nanoTime());
		project.create(null);
		project.open(null);
		java.nio.file.Path sourceFolder = folder.toPath();
		java.nio.file.Path destFolder = project.getLocation().toFile().toPath();

		Files.walk(sourceFolder).forEach(source -> {
			try {
				Files.copy(source, destFolder.resolve(sourceFolder.relativize(source)), StandardCopyOption.REPLACE_EXISTING);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		return project;
	}
	return null;
}
 
Example #21
Source File: JImageGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static Path addFiles(Path module, InMemoryFile... resources) throws IOException {
    Path tempFile = Files.createTempFile("jlink-test", "");
    try (JarInputStream in = new JarInputStream(Files.newInputStream(module));
         JarOutputStream out = new JarOutputStream(new FileOutputStream(tempFile.toFile()))) {
        ZipEntry entry;
        while ((entry = in.getNextEntry()) != null) {
            String name = entry.getName();
            out.putNextEntry(new ZipEntry(name));
            copy(in, out);
            out.closeEntry();
        }
        for (InMemoryFile r : resources) {
            addFile(r, out);
        }
    }
    Files.move(tempFile, module, StandardCopyOption.REPLACE_EXISTING);
    return module;
}
 
Example #22
Source File: ControlRemoteProfilesPreferencePage.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private void copyProfileFile(Path source, Path destPath, String errorTitle) {
    Path destFile = destPath.resolve(source.getFileName());
    if (destFile.toFile().exists()) {
        boolean overwrite = MessageDialog.openConfirm(getShell(),
                Messages.TraceControl_ProfileAlreadyExists,
                NLS.bind(Messages.TraceControl_OverwriteQuery, destFile.getFileName()));

        if (!overwrite) {
            return;
        }
    }
    try {
        Files.copy(source, destFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e1) {
        MessageDialog.openError(getShell(),
                errorTitle,
                "Error copying profile:\n" + e1.toString()); //$NON-NLS-1$
    }
}
 
Example #23
Source File: ClientUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
public static File getExtensionBundleVersionContent(final Response response, final File outputDirectory) {
    final String contentDispositionHeader = response.getHeaderString("Content-Disposition");
    if (StringUtils.isBlank(contentDispositionHeader)) {
        throw new IllegalStateException("Content-Disposition header was blank or missing");
    }

    final int equalsIndex = contentDispositionHeader.lastIndexOf("=");
    final String filename = contentDispositionHeader.substring(equalsIndex + 1).trim();
    final File bundleFile = new File(outputDirectory, filename);

    try (final InputStream responseInputStream = response.readEntity(InputStream.class)) {
        Files.copy(responseInputStream, bundleFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return bundleFile;
    } catch (Exception e) {
        throw new IllegalStateException("Unable to write bundle content due to: " + e.getMessage(), e);
    }
}
 
Example #24
Source File: ReplayCacheTestProc.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static Ex round(int i, int old, int server, boolean expected)
        throws Exception {
    ps[server].println("TEST");
    ps[server].println(reqs.get(old).msg);
    String reply = ps[server].readData();
    Ex result = new Ex();
    result.i = i;
    result.expected = expected;
    result.server = ps[server].debug();
    result.actual = Boolean.valueOf(reply);
    result.user = reqs.get(old).user;
    result.peer = reqs.get(old).peer;
    result.old = old;
    result.csize = csize(result.peer);
    result.hash = hash(reqs.get(old).msg);
    if (new File(dfl(result.peer)).exists()) {
        Files.copy(Paths.get(dfl(result.peer)), Paths.get(
            String.format("%03d-USER%d-host%d-%s-%s",
                i, result.user, result.peer, result.server,
                result.actual)
            + "-" + result.hash),
            StandardCopyOption.COPY_ATTRIBUTES);
    }
    return result;
}
 
Example #25
Source File: FixProjectsUtils.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
public static void setClasspath(IClasspathEntry[] classpath, IJavaProject javaProject, IProgressMonitor monitor) throws JavaModelException
{
	// backup .classpath
	File classPathFileBak = javaProject.getProject().getFile(".classpath.bak").getLocation().toFile();
	if (!classPathFileBak.exists())
	{
		File classPathFile = javaProject.getProject().getFile(".classpath").getLocation().toFile();
		try {
			Files.copy(Paths.get(classPathFile.getAbsolutePath()), Paths.get(classPathFileBak.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
		}
		catch (IOException e) {
			// can't back up file but we should continue anyway
			Activator.log("Failed to backup classfile [" + classPathFile.getAbsolutePath() + "]");
		}
	}
	javaProject.setRawClasspath(classpath, monitor);	
}
 
Example #26
Source File: IgnitePdsBinaryMetadataOnClusterRestartTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** */
private void copyIncompatibleBinaryMetadata(String fromWorkDir,
    String fromConsId,
    String toWorkDir,
    String toConsId,
    String fileName
) throws Exception {
    String workDir = U.defaultWorkDirectory();

    Path fromFile = Paths.get(workDir, fromWorkDir, DataStorageConfiguration.DFLT_BINARY_METADATA_PATH,
        fromConsId, fileName);
    Path toFile = Paths.get(workDir, toWorkDir, DataStorageConfiguration.DFLT_BINARY_METADATA_PATH,
        toConsId, fileName);

    Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING);
}
 
Example #27
Source File: ComponentUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JPopupMenu getComponentPopupMenu() {
    WebPopupMenu menu = new WebPopupMenu();

    if (mFile == null)
        return null; // should never happen

    WebMenuItem saveMenuItem = new WebMenuItem(Tr.tr("Save File As…"));
    saveMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            if (mFile == null)
                return; // should never happen

            File suggestedFile = new File(
                    mFileChooser.getCurrentDirectory(), mFile.getName());

            mFileChooser.setSelectedFile(suggestedFile);
            // fix WebLaf bug
            mFileChooser.getFileChooserPanel().setSelectedFiles(new File[]{suggestedFile});

            int option = mFileChooser.showSaveDialog(AttachmentPanel.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                try {
                    Files.copy(mFile.toPath(), mFileChooser.getSelectedFile().toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException ex) {
                    LOGGER.log(Level.WARNING, "can't copy file", ex);
                }
            }
        }
    });
    if (!mFile.exists()) {
        saveMenuItem.setEnabled(false);
        saveMenuItem.setToolTipText(Tr.tr("File does not exist"));
    }
    menu.add(saveMenuItem);

    return menu;
}
 
Example #28
Source File: TestCombineManifest.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
public void convertDirectoryMadnessZipped() throws Exception {
	Path file = Files.createTempFile("DirectoryMadnessZipped", ".omex");
	try (InputStream src = getClass().getResourceAsStream(
			"/combine/DirectoryMadnessZipped-skeleton.omex")) {
		Files.copy(src, file, StandardCopyOption.REPLACE_EXISTING);
	}
	//System.out.println(file);
	try (Bundle bundle = Bundles.openBundle(file)) {

	}
}
 
Example #29
Source File: LocalFileSystem.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
protected void rename(List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds)
    throws IOException {
  checkArgument(
      srcResourceIds.size() == destResourceIds.size(),
      "Number of source files %s must equal number of destination files %s",
      srcResourceIds.size(),
      destResourceIds.size());
  int numFiles = srcResourceIds.size();
  for (int i = 0; i < numFiles; i++) {
    LocalResourceId src = srcResourceIds.get(i);
    LocalResourceId dst = destResourceIds.get(i);
    LOG.debug("Renaming {} to {}", src, dst);
    File parent = dst.getCurrentDirectory().getPath().toFile();
    if (!parent.exists()) {
      checkArgument(
          parent.mkdirs() || parent.exists(),
          "Unable to make output directory %s in order to move into file %s",
          parent,
          dst.getPath());
    }
    // Rename the source file, replacing the existing destination.
    Files.move(
        src.getPath(),
        dst.getPath(),
        StandardCopyOption.REPLACE_EXISTING,
        StandardCopyOption.ATOMIC_MOVE);
  }
}
 
Example #30
Source File: ConfigurationPersisterFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void successfulBoot() throws ConfigurationPersistenceException {
    if (successfulBoot.compareAndSet(false, true)) {
        try {
            Files.move(bootFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            HostControllerLogger.ROOT_LOGGER.cannotRenameCachedDomainXmlOnBoot(bootFile.getName(), file.getName(), e.getMessage());
            throw new ConfigurationPersistenceException(e);
        }
    }
}