List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:math.tools.Browse.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if (table[jTable1.getSelectedRow()][3] == "Not Downloaded Yet") { System.out.println("downloading"); FileOutputStream fos; try {//from w w w .j av a 2 s. co m URL website = new URL("" + table[jTable1.getSelectedRow()][4]); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(System.getProperty("user.home") + "//MathHelper//tools//" + table[jTable1.getSelectedRow()][0] + ".jar"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } } try { Runtime.getRuntime().exec("java -jar " + System.getProperty("user.home") + "//MathHelper//tools//" + table[jTable1.getSelectedRow()][0] + ".jar"); } catch (IOException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.gdms.driver.dbf.DBFDriver.java
@Override public void createSource(String path, Metadata metadata, DataSourceFactory dataSourceFactory) throws DriverException { LOG.trace("Creating source file"); try {// ww w .j ava 2 s . co m FileOutputStream fos = new FileOutputStream(new File(path)); DbaseFileHeader header = getHeader(metadata, 0); DbaseFileWriter writer = new DbaseFileWriter(header, fos.getChannel()); writer.close(); } catch (IOException e) { throw new DriverException(e); } catch (DbaseFileException e) { throw new DriverException(e); } }
From source file:dk.netarkivet.common.utils.FileUtils.java
/** * Copy file from one location to another. Will silently overwrite an * already existing file./*from w w w . j a v a 2 s .c o m*/ * * @param from * original to copy * @param to * destination of copy * @throws IOFailure if an io error occurs while copying file, * or the original file does not exist. */ public static void copyFile(File from, File to) { ArgumentNotValid.checkNotNull(from, "File from"); ArgumentNotValid.checkNotNull(to, "File to"); if (!from.exists()) { String errMsg = "Original file '" + from.getAbsolutePath() + "' does not exist"; log.warn(errMsg); throw new IOFailure(errMsg); } try { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel in = null; FileChannel out = null; try { inStream = new FileInputStream(from); outStream = new FileOutputStream(to); in = inStream.getChannel(); out = outStream.getChannel(); long bytesTransferred = 0; do { //Note: in.size() is called every loop, because if it should //change size, we might end up in an infinite loop trying to //copy more bytes than are actually available. bytesTransferred += in.transferTo(bytesTransferred, Math.min(Constants.IO_CHUNK_SIZE, in.size() - bytesTransferred), out); } while (bytesTransferred < in.size()); } finally { if (inStream != null) { inStream.close(); } if (outStream != null) { outStream.close(); } if (in != null) { in.close(); } if (out != null) { out.close(); } } } catch (IOException e) { final String errMsg = "Error copying file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath() + "'"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } }
From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java
private void cleanOldDataDirectories(File parentDirectory) { for (final File dir : parentDirectory.listFiles()) { if (!dir.isDirectory()) { continue; }/*from www.j a v a 2 s.c o m*/ final File lockFile = new File(dir, LOCK_FILE_NAME); if (!lockFile.exists()) { continue; } try { final FileOutputStream fos = new FileOutputStream(lockFile); try { try (FileLock lock = fos.getChannel().tryLock()) { if (lock != null) { LOG.info("Found stale data directory {}", dir); if (new File(dir, "postmaster.pid").exists()) { try { pgCtl(dir, "stop"); LOG.info("Shut down orphaned postmaster!"); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.warn("Failed to stop postmaster " + dir, e); } else { LOG.warn("Failed to stop postmaster " + dir + ": " + e.getMessage()); } } } FileUtils.deleteDirectory(dir); } } } finally { fos.close(); } } catch (final OverlappingFileLockException e) { // The directory belongs to another instance in this VM. LOG.trace("While cleaning old data directories", e); } catch (final Exception e) { LOG.warn("While cleaning old data directories", e); } } }
From source file:org.alfresco.filesys.repo.CommandExecutorImpl.java
/** * @param sess SrvSession// w w w. j a v a 2 s .c o m * @param tree TreeConnection * @param command Command * @param result Object * @return Object * @throws IOException */ private Object executeInternal(SrvSession sess, TreeConnection tree, Command command, Object result) throws IOException { FileFilterMode.setClient(ClientHelper.getClient(sess)); try { if (command instanceof CompoundCommand) { Object ret = null; logger.debug("compound command received"); CompoundCommand x = (CompoundCommand) command; for (Command compoundPart : x.getCommands()) { logger.debug("running part of compound command"); Object val = executeInternal(sess, tree, compoundPart, result); if (val != null) { // Return the value from the last command. ret = val; } } return ret; } else if (command instanceof CreateFileCommand) { logger.debug("create file command"); CreateFileCommand create = (CreateFileCommand) command; return repositoryDiskInterface.createFile(create.getRootNode(), create.getPath(), create.getAllocationSize(), create.isHidden()); } else if (command instanceof RestoreFileCommand) { logger.debug("restore file command"); RestoreFileCommand restore = (RestoreFileCommand) command; return repositoryDiskInterface.restoreFile(sess, tree, restore.getRootNode(), restore.getPath(), restore.getAllocationSize(), restore.getOriginalNodeRef()); } else if (command instanceof DeleteFileCommand) { logger.debug("delete file command"); DeleteFileCommand delete = (DeleteFileCommand) command; return repositoryDiskInterface.deleteFile2(sess, tree, delete.getRootNode(), delete.getPath()); } else if (command instanceof OpenFileCommand) { logger.debug("open file command"); OpenFileCommand o = (OpenFileCommand) command; OpenFileMode mode = o.getMode(); return repositoryDiskInterface.openFile(sess, tree, o.getRootNodeRef(), o.getPath(), mode, o.isTruncate()); } else if (command instanceof CloseFileCommand) { logger.debug("close file command"); CloseFileCommand c = (CloseFileCommand) command; return repositoryDiskInterface.closeFile(tree, c.getRootNodeRef(), c.getPath(), c.getNetworkFile()); } else if (command instanceof ReduceQuotaCommand) { logger.debug("reduceQuota file command"); ReduceQuotaCommand r = (ReduceQuotaCommand) command; repositoryDiskInterface.reduceQuota(sess, tree, r.getNetworkFile()); } else if (command instanceof RenameFileCommand) { logger.debug("rename command"); RenameFileCommand rename = (RenameFileCommand) command; repositoryDiskInterface.renameFile(rename.getRootNode(), rename.getFromPath(), rename.getToPath(), rename.isSoft(), false); } else if (command instanceof MoveFileCommand) { logger.debug("move command"); MoveFileCommand move = (MoveFileCommand) command; repositoryDiskInterface.renameFile(move.getRootNode(), move.getFromPath(), move.getToPath(), false, move.isMoveAsSystem()); } else if (command instanceof CopyContentCommand) { if (logger.isDebugEnabled()) { logger.debug("Copy content command - copy content"); } CopyContentCommand copy = (CopyContentCommand) command; repositoryDiskInterface.copyContent(copy.getRootNode(), copy.getFromPath(), copy.getToPath()); } else if (command instanceof DoNothingCommand) { if (logger.isDebugEnabled()) { logger.debug("Do Nothing Command - doing nothing"); } } else if (command instanceof ResultCallback) { if (logger.isDebugEnabled()) { logger.debug("Result Callback"); } ResultCallback callback = (ResultCallback) command; callback.execute(result); } else if (command instanceof RemoveTempFileCommand) { RemoveTempFileCommand r = (RemoveTempFileCommand) command; if (logger.isDebugEnabled()) { logger.debug("Remove Temp File:" + r.getNetworkFile()); } File file = r.getNetworkFile().getFile(); boolean isDeleted = file.delete(); if (!isDeleted) { logger.debug("unable to delete temp file:" + r.getNetworkFile() + ", closed=" + r.getNetworkFile().isClosed()); /* * Unable to delete temporary file * Could be a bug with the file handle not being closed, but yourkit does not * find anything awry. * There are reported Windows JVM bugs such as 4715154 ... */ FileOutputStream fos = new FileOutputStream(file); FileChannel outChan = null; try { outChan = fos.getChannel(); outChan.truncate(0); } catch (IOException e) { logger.debug("unable to clean up file", e); } finally { if (outChan != null) { try { outChan.close(); } catch (IOException e) { } } fos.close(); } } } else if (command instanceof ReturnValueCommand) { ReturnValueCommand r = (ReturnValueCommand) command; if (logger.isDebugEnabled()) { logger.debug("Return value"); } return r.getReturnValue(); } else if (command instanceof RemoveNoContentFileOnError) { RemoveNoContentFileOnError r = (RemoveNoContentFileOnError) command; if (logger.isDebugEnabled()) { logger.debug("Remove no content file on error"); } repositoryDiskInterface.deleteEmptyFile(r.getRootNodeRef(), r.getPath()); } } finally { FileFilterMode.clearClient(); } return null; }
From source file:com.opentable.db.postgres.embedded.EmbeddedPostgreSQL.java
private void cleanOldDataDirectories(File parentDirectory) { for (final File dir : parentDirectory.listFiles()) { if (!dir.isDirectory()) { continue; }/*from w w w. j av a 2s .c o m*/ final File lockFile = new File(dir, LOCK_FILE_NAME); final boolean isTooNew = System.currentTimeMillis() - lockFile.lastModified() < 10 * 60 * 1000; if (!lockFile.exists() || isTooNew) { continue; } try { final FileOutputStream fos = new FileOutputStream(lockFile); try { try (FileLock lock = fos.getChannel().tryLock()) { if (lock != null) { LOG.info("Found stale data directory {}", dir); if (new File(dir, "postmaster.pid").exists()) { try { pgCtl(dir, "stop"); LOG.info("Shut down orphaned postmaster!"); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.warn("Failed to stop postmaster " + dir, e); } else { LOG.warn("Failed to stop postmaster " + dir + ": " + e.getMessage()); } } } FileUtils.deleteDirectory(dir); } } } finally { fos.close(); } } catch (final OverlappingFileLockException e) { // The directory belongs to another instance in this VM. LOG.trace("While cleaning old data directories", e); } catch (final Exception e) { LOG.warn("While cleaning old data directories", e); } } }
From source file:com.castlabs.csf.cff.CreateStreamingDeliveryTargetFileset.java
@Override public int run() throws Exception { logger = setupLogger();//from w w w . ja va2s . c o m if (encKid != null) { this.keyid = UUID.fromString(this.encKid); this.cek = new SecretKeySpec(Hex.decodeHex(this.encKeySecretKey), "AES"); } Map<Track, String> trackOriginalFilename = setupTracks(); FragmentIntersectionFinder intersectionFinder = getFragmentStartSamples(trackOriginalFilename); Map<Track, String> filenames = generateFilenames(trackOriginalFilename); StreamingDeliveryTargetMp4Builder mp4Builder = new StreamingDeliveryTargetMp4Builder(); mp4Builder.setIntersectionFinder(intersectionFinder); Movie m = new Movie(); for (Map.Entry<Track, String> e : trackOriginalFilename.entrySet()) { if (keyid != null) { m.setTracks(Collections.<Track>singletonList(new CencEncryptingTrackImpl(e.getKey(), keyid, cek))); } else { m.setTracks(Collections.<Track>singletonList(e.getKey())); } String apid = "urn:dece:apid:org:castlabs:" + FilenameUtils.getBaseName(e.getValue()); mp4Builder.setApid(apid); Container c = mp4Builder.build(m); String filename = filenames.get(e.getKey()); FileOutputStream fos = new FileOutputStream(filename); logger.info(String.format("Writing %s (track_ID=%d, apid=%s)", filename, e.getKey().getTrackMetaData().getTrackId(), apid)); c.writeContainer(fos.getChannel()); fos.close(); } return 0; }
From source file:eu.stratosphere.nephele.checkpointing.WriteThread.java
private FileChannel getMetaDataFileChannel(final String suffix) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Writing checkpointing meta data to directory " + this.checkpointPath); }// w ww. java2 s .c o m // Bypass FileSystem API for local checkpoints if (!this.distributed) { final FileOutputStream fos = new FileOutputStream(this.checkpointPath.toUri().getPath() + Path.SEPARATOR + CheckpointUtils.METADATA_PREFIX + "_" + this.vertexID + suffix); return fos.getChannel(); } return new FileChannelWrapper(this.fileSystem, this.checkpointPath .suffix(Path.SEPARATOR + CheckpointUtils.METADATA_PREFIX + "_" + this.vertexID + suffix), BUFFER_SIZE, (short) 2); // TODO: // Make // replication // configurable }
From source file:math.tools.Browse.java
/** * Creates new form jsontable/* w ww .j a v a2 s.c o m*/ */ public Browse() { BufferedReader in; FileOutputStream fos; new File(System.getProperty("user.home") + "//MathHelper//tools//").mkdirs(); try { URL website = new URL("https://dl.dropboxusercontent.com/u/67622419/mathTools/toolInfo.json"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(System.getProperty("user.home") + "//MathHelper//toolInfo.json"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } try { in = new BufferedReader( new FileReader(System.getProperty("user.home") + "//MathHelper//toolInfo.json")); String inputLine; int i = -1; JSONObject json; while ((inputLine = in.readLine()) != null) { i++; json = (JSONObject) new JSONParser().parse(inputLine); table[i][0] = json.get("name"); table[i][1] = json.get("author"); table[i][2] = json.get("rating"); File f = new File( System.getProperty("user.home") + "//MathHelper//tools//" + json.get("name") + ".jar"); if (!f.exists()) { table[i][3] = "Not Downloaded Yet"; } else { table[i][3] = "Downloaded"; } table[i][4] = json.get("adress"); } in.close(); } catch (IOException | ParseException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } initComponents(); }
From source file:org.gdms.driver.dbf.DBFDriver.java
public void writeFile(File file, RowProvider dataSource, ProgressMonitor pm) throws DriverException { LOG.trace("Writing source file"); try {//from w w w. j ava 2s. c o m FileOutputStream fos = new FileOutputStream(file); DbaseFileHeader header = getHeader(dataSource.getMetadata(), (int) dataSource.getRowCount()); DbaseFileWriter writer = new DbaseFileWriter(header, fos.getChannel()); final int numRecords = header.getNumRecords(); pm.startTask("Writing file", numRecords); for (int i = 0; i < numRecords; i++) { if (i >= 100 && i % 100 == 0) { if (pm.isCancelled()) { break; } else { pm.progressTo(i); } } writer.write(dataSource.getRow(i)); } pm.progressTo(numRecords); writer.close(); } catch (IOException e) { throw new DriverException(e); } catch (DbaseFileException e) { throw new DriverException(e); } pm.endTask(); }