List of usage examples for java.nio.file Files copy
public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
From source file:dialog.DialogFunctionUser.java
private void actionAddUserNoController() { if (!isValidData()) { return;/* w w w . jav a 2s .co m*/ } if (isExistUsername(tfUsername.getText())) { JOptionPane.showMessageDialog(null, "Username tn ti", "Error", JOptionPane.ERROR_MESSAGE); return; } String username = tfUsername.getText(); String fullname = tfFullname.getText(); String password = new String(tfPassword.getPassword()); password = LibraryString.md5(password); int role = cbRole.getSelectedIndex(); User objUser; if (mAvatar != null) { objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role, new Date(System.currentTimeMillis()), mAvatar.getPath()); String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "." + FilenameUtils.getExtension(mAvatar.getName()); Path source = Paths.get(mAvatar.toURI()); Path destination = Paths.get("files/" + fileName); try { Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex); } } else { objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role, new Date(System.currentTimeMillis()), ""); } if ((new ModelUser()).addItem(objUser)) { ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Thm thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Thm tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } this.dispose(); }
From source file:com.anritsu.mcreleaseportal.utils.FileUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j av a2 s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.setAttribute("mcPackage", null); PrintWriter pw = response.getWriter(); response.setContentType("text/plain"); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); // Save input stream file for later use File dir = new File(Configuration.getInstance().getSavePath()); if (!dir.exists() && !dir.isDirectory()) { dir.mkdir(); LOGGER.log(Level.INFO, "Changes.xml archive directory was created at " + dir.getAbsolutePath()); } String fileName = request.getSession().getId() + "_" + System.currentTimeMillis(); File file = new File(dir, fileName); file.createNewFile(); Path path = file.toPath(); Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING); LOGGER.log(Level.INFO, "changes.xml saved on disk as: " + file.getAbsolutePath()); // Save filename to session for next calls session.setAttribute("xmlFileLocation", file.getAbsolutePath()); LOGGER.log(Level.INFO, "changes.xml saved on session as: fileName:" + file.getAbsolutePath()); // Cleanup stream.close(); } } catch (FileUploadException | IOException | RuntimeException e) { pw.println( "An error occurred when trying to process uploaded file! \n Please check the file consistency and try to re-submit. \n If the error persist pleace contact system administrator!"); } }
From source file:ch.silviowangler.dox.web.admin.RepositoryControllerTest.java
@Test public void testGetDocument2() throws Exception { final File file = folder.newFile("hello.txt"); InputStream in = new ByteArrayInputStream("hello".getBytes()); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); when(response.getOutputStream()).thenReturn(outputStream); doThrow(new IOException()).when(outputStream).write(any(byte[].class), any(int.class), any(int.class)); when(doxExporter.export()).thenReturn(file); when(mimeTypes.getProperty("zip")).thenReturn("my content type"); controller.getDocument(this.response); verify(response).setStatus(SC_INTERNAL_SERVER_ERROR); }
From source file:org.ng200.openolympus.controller.task.TaskFilesystemManipulatingController.java
@PreAuthorize(SecurityExpressionConstants.IS_ADMIN) private void extractZipFile(final InputStream zipFile, final Path destination) throws Exception { try (ArchiveInputStream input = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(zipFile))) { ArchiveEntry entry;/*from w ww . ja v a 2s .c o m*/ while ((entry = input.getNextEntry()) != null) { final Path dest = destination.resolve(entry.getName()); if (entry.isDirectory()) { FileAccess.createDirectories(dest); } else { FileAccess.createDirectories(dest.getParent()); FileAccess.createFile(dest); Files.copy(input, dest, StandardCopyOption.REPLACE_EXISTING); } } } }
From source file:de._692b8c32.cdlauncher.tasks.GoogleDownloadTask.java
@Override public void doWork() { setProgress(-1);// w w w . ja v a2s . c om try { HttpClient client = HttpClients.createDefault(); String realUrl = null; Pattern pattern = Pattern.compile( "<a id=\"uc-download-link\" class=\"goog-inline-block jfk-button jfk-button-action\" href=\"([^\"]*)\">"); try (BufferedReader reader = new BufferedReader( new InputStreamReader(client.execute(new HttpGet(fileUrl)).getEntity().getContent()))) { for (String line : reader.lines().collect(Collectors.toList())) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { realUrl = fileUrl.substring(0, fileUrl.lastIndexOf('/')) + matcher.group(1).replace("&", "&"); break; } } } if (realUrl == null) { throw new RuntimeException("Failed to find real url"); } else { try (InputStream stream = client.execute(new HttpGet(realUrl)).getEntity().getContent()) { Files.copy(stream, cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } } catch (IOException ex) { throw new RuntimeException("Could not download data", ex); } }
From source file:io.github.zlika.reproducible.ZipStripper.java
@Override public void strip(File in, File out) throws IOException { try (final ZipFile zip = new ZipFile(in); final ZipArchiveOutputStream zout = new ZipArchiveOutputStream(out)) { final List<String> sortedNames = sortEntriesByName(zip.getEntries()); for (String name : sortedNames) { final ZipArchiveEntry entry = zip.getEntry(name); // Strip Zip entry final ZipArchiveEntry strippedEntry = filterZipEntry(entry); // Strip file if required final Stripper stripper = getSubFilter(name); if (stripper != null) { // Unzip entry to temp file final File tmp = File.createTempFile("tmp", null); tmp.deleteOnExit();/*from w w w . j a va 2 s. com*/ Files.copy(zip.getInputStream(entry), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING); final File tmp2 = File.createTempFile("tmp", null); tmp2.deleteOnExit(); stripper.strip(tmp, tmp2); final byte[] fileContent = Files.readAllBytes(tmp2.toPath()); strippedEntry.setSize(fileContent.length); zout.putArchiveEntry(strippedEntry); zout.write(fileContent); zout.closeArchiveEntry(); } else { // Copy the Zip entry as-is zout.addRawArchiveEntry(strippedEntry, getRawInputStream(zip, entry)); } } } }
From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java
/** * @see WorkspaceFileHandler#copyFile(java.io.File, java.io.File) *//*from w w w .j a v a2 s . c om*/ @Override public void copyFile(File originNodeFile, File targetNodeFile) throws IOException { Files.copy(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:controladores.subirArchivo.java
public void guardarPrime() { try {//from w w w .j a v a2s.c o m //guardar los datos //??????????? //guardando los requisitos for (UploadedFile f : files) { if (f != null) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateobj = new Date(); String nombreFecha = ("chiting" + "-" + df.format(dateobj).replaceAll(":", "-")).trim(); File directorio = new File("d:/Postgrado/inscripciones/requisitos/" + nombreFecha); if (!directorio.exists()) { directorio.mkdir(); } String filename = f.getFileName(); // String extension = f.getContentType(); Path ruta = Paths.get(directorio + filename); try (InputStream input = f.getInputstream()) { Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING); } FacesMessage message = new FacesMessage("Succesful", filename + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, message); } } } catch (Exception ex) { Logger.getLogger(subirArchivo.class.getName()).log(Level.SEVERE, null, ex); FacesMessage message = new FacesMessage("Succesful", ex.toString()); FacesContext.getCurrentInstance().addMessage(null, message); } }
From source file:dk.ekot.misc.SynchronizedCache.java
protected void copy(Path fullSourcePath, Path fullCachePath) throws IOException { Files.createDirectories(fullCachePath.getParent()); Files.copy(fullSourcePath, fullCachePath, StandardCopyOption.REPLACE_EXISTING); }
From source file:org.schedulesdirect.grabber.LogoTask.java
@Override public void run() { if (req != null && url != null) { long start = System.currentTimeMillis(); try {//from w w w. ja va 2 s. c om HttpResponse resp = Request.Get(url.toURI()).execute().returnResponse(); StatusLine status = resp.getStatusLine(); if (status.getStatusCode() == 200) { try (InputStream ins = resp.getEntity().getContent()) { Path p = vfs.getPath("logos", String.format("%s.%s", callsign, ext)); Files.copy(ins, p, StandardCopyOption.REPLACE_EXISTING); if (md5 != null) synchronized (cache) { cache.put(callsign, md5); } if (LOG.isTraceEnabled()) LOG.trace(String.format("LogoTask COMPLETE for %s [%dms]", callsign, System.currentTimeMillis() - start)); } } else { LOG.warn(String.format("Received error response for logo '%s': %s", callsign, resp.getStatusLine())); if (status.getStatusCode() >= 400 && status.getStatusCode() <= 499) removeStaleLogo(); } } catch (IOException | URISyntaxException e) { LOG.error(String.format("IOError grabbing logo for %s", callsign), e); } } else if (LOG.isTraceEnabled()) LOG.trace(String.format("No logo info for %s", callsign)); }