List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:csic.ceab.movelab.beepath.Util.java
/** * Saves a byte array to the internal storage directory. * /*from w w w.j av a2s. c om*/ * @param context * The application context. * @param filename * The file name to use. * @param bytes * The byte array to be saved. */ public static void saveJSON(Context context, String dir, String fileprefix, String inputString) { // String TAG = "Util.saveFile"; FileOutputStream fos = null; FileLock lock = null; try { byte[] bytes = inputString.getBytes("UTF-8"); File directory = new File(context.getFilesDir().getAbsolutePath(), dir); directory.mkdirs(); File target = new File(directory, fileprefix + System.currentTimeMillis() + ".txt"); fos = new FileOutputStream(target); lock = fos.getChannel().lock(); fos.write(bytes); } catch (IOException e) { // logging exception but doing nothing // Log.e(TAG, "Exception " + e); } finally { if (lock != null) { try { lock.release(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { // logging exception but doing nothing // Log.e(TAG, "Exception " + e); } } } }
From source file:uk.codingbadgers.bootstrap.download.EtagDownload.java
public void download() { CloseableHttpClient client = HttpClients.createDefault(); HttpGet assetRequest = new HttpGet(remote); assetRequest.setHeader(new BasicHeader("Accept", BootstrapConstants.ASSET_MIME_TYPE)); if (local.exists()) { assetRequest/*from w w w.j a va 2s . co m*/ .setHeader(new BasicHeader("If-None-Match", "\"" + ChecksumGenerator.createMD5(local) + "\"")); } try { HttpResponse response = client.execute(assetRequest); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { // No need to download, its already latest System.out.println("File " + local.getName() + " is up to date with remote, no need to download"); } else if (status.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || status.getStatusCode() == HttpStatus.SC_OK) { // Update local version System.err.println("Downloading " + local.getName()); HttpEntity entity = response.getEntity(); ReadableByteChannel rbc = Channels.newChannel(entity.getContent()); FileOutputStream fos = new FileOutputStream(local); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); EntityUtils.consume(entity); String hash = "\"" + ChecksumGenerator.createMD5(local) + "\""; if (!hash.equalsIgnoreCase(response.getFirstHeader("Etag").getValue())) { throw new BootstrapException( "Error downloading file (" + local.getName() + ")\n[expected hash: " + response.getFirstHeader("Etag").getValue() + " but got " + hash + "]"); } System.out.println("Downloaded " + local.getName()); } else { throw new BootstrapException("Error getting update from github. Error: " + status.getStatusCode() + status.getReasonPhrase()); } } catch (IOException ex) { throw new BootstrapException(ex); } finally { close(client); } }
From source file:uk.codingbadgers.bootstrap.download.Sha1Download.java
@Override public void download() { CloseableHttpClient client = HttpClients.createDefault(); String hash = null;//from ww w .j av a 2 s .c om // Get sha1 hash from repo try { HttpGet request = new HttpGet(remote + ".sha1"); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); hash = EntityUtils.toString(entity); EntityUtils.consume(entity); } } catch (IOException ex) { throw new BootstrapException(ex); } if (local.exists()) { String localHash = ChecksumGenerator.createSha1(local); if (hash != null && hash.equalsIgnoreCase(localHash)) { System.out.println("File " + local.getName() + " is up to date with remote, no need to download"); return; } } if (!local.getParentFile().exists()) { local.getParentFile().mkdirs(); } // Download library from remote try { HttpGet request = new HttpGet(remote); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { System.err.println("Downloading " + local.getName()); HttpEntity entity = response.getEntity(); ReadableByteChannel rbc = Channels.newChannel(entity.getContent()); FileOutputStream fos = new FileOutputStream(local); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); EntityUtils.consume(entity); String localHash = ChecksumGenerator.createSha1(local); if (hash != null && !localHash.equalsIgnoreCase(hash)) { throw new BootstrapException("Error downloading file (" + local.getName() + ")\n[expected hash: " + localHash + " but got " + hash + "]"); } System.out.println("Downloaded " + local.getName()); } else { throw new BootstrapException("Error download update for " + local.getName() + ", Error: " + status.getStatusCode() + status.getReasonPhrase()); } } catch (IOException ex) { throw new BootstrapException(ex); } }
From source file:net.zyuiop.fastsurvival.FastSurvival.java
private boolean checkLibraries() { try {//from w w w .ja v a 2 s . c o m Class clazz = Class.forName("org.apache.commons.lang3.StringUtils"); } catch (ClassNotFoundException e) { Bukkit.getLogger().info("Missing libraries, downloading them."); try { URL url = new URL("http://static.zyuiop.net/libs.jar"); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); File output = new File(getFile().getParentFile(), "libs.jar"); FileOutputStream fos = new FileOutputStream(output); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); Bukkit.getLogger().info("Downloaded, loading..."); getPluginLoader().enablePlugin(getPluginLoader().loadPlugin(output)); Bukkit.getLogger().info("Done !"); } catch (InvalidPluginException | IOException e1) { Bukkit.getLogger().severe("Libraries download failed. Stopping."); e1.printStackTrace(); return false; } } return true; }
From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java
private static void writeSubmissionManifest(EncryptedFormInformation formInfo, File submissionXml, List<File> mediaFiles) throws EncryptionException { Document d = new Document(); d.setStandalone(true);/*from w w w.j av a 2s . c om*/ d.setEncoding(UTF_8); Element e = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, DATA); e.setPrefix(null, XML_ENCRYPTED_TAG_NAMESPACE); e.setAttribute(null, ID, formInfo.formId); if (formInfo.formVersion != null) { e.setAttribute(null, VERSION, formInfo.formVersion); } e.setAttribute(null, ENCRYPTED, "yes"); d.addChild(0, Node.ELEMENT, e); int idx = 0; Element c; c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY); c.addChild(0, Node.TEXT, formInfo.base64RsaEncryptedSymmetricKey); e.addChild(idx++, Node.ELEMENT, c); c = d.createElement(XML_OPENROSA_NAMESPACE, META); c.setPrefix("orx", XML_OPENROSA_NAMESPACE); { Element instanceTag = d.createElement(XML_OPENROSA_NAMESPACE, INSTANCE_ID); instanceTag.addChild(0, Node.TEXT, formInfo.instanceMetadata.instanceId); c.addChild(0, Node.ELEMENT, instanceTag); } e.addChild(idx++, Node.ELEMENT, c); e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); if (mediaFiles != null) { for (File file : mediaFiles) { c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA); Element fileTag = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, FILE); fileTag.addChild(0, Node.TEXT, file.getName() + ".enc"); c.addChild(0, Node.ELEMENT, fileTag); e.addChild(idx++, Node.ELEMENT, c); e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); } } c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE); c.addChild(0, Node.TEXT, submissionXml.getName() + ".enc"); e.addChild(idx++, Node.ELEMENT, c); c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE); c.addChild(0, Node.TEXT, formInfo.getBase64EncryptedElementSignature()); e.addChild(idx++, Node.ELEMENT, c); FileOutputStream fout = null; OutputStreamWriter writer = null; try { fout = new FileOutputStream(submissionXml); writer = new OutputStreamWriter(fout, UTF_8); KXmlSerializer serializer = new KXmlSerializer(); serializer.setOutput(writer); // setting the response content type emits the xml header. // just write the body here... d.writeChildren(serializer); serializer.flush(); writer.flush(); fout.getChannel().force(true); writer.close(); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName(); Log.e(t, msg); throw new EncryptionException(msg, ex); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(fout); } }
From source file:org.apache.nifi.file.FileUtils.java
/** * Copies the given source file to the given destination file. The given * destination will be overwritten if it already exists. * * @param source/*w w w . j a va2s.com*/ * @param destination * @param lockInputFile if true will lock input file during copy; if false * will not * @param lockOutputFile if true will lock output file during copy; if false * will not * @param move if true will perform what is effectively a move operation * rather than a pure copy. This allows for potentially highly efficient * movement of the file but if not possible this will revert to a copy then * delete behavior. If false, then the file is copied and the source file is * retained. If a true rename/move occurs then no lock is held during that * time. * @param logger if failures occur, they will be logged to this logger if * possible. If this logger is null, an IOException will instead be thrown, * indicating the problem. * @return long number of bytes copied * @throws FileNotFoundException if the source file could not be found * @throws IOException * @throws SecurityException if a security manager denies the needed file * operations */ public static long copyFile(final File source, final File destination, final boolean lockInputFile, final boolean lockOutputFile, final boolean move, final Logger logger) throws FileNotFoundException, IOException { FileInputStream fis = null; FileOutputStream fos = null; FileLock inLock = null; FileLock outLock = null; long fileSize = 0L; if (!source.canRead()) { throw new IOException("Must at least have read permission"); } if (move && source.renameTo(destination)) { fileSize = destination.length(); } else { try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); final FileChannel in = fis.getChannel(); final FileChannel out = fos.getChannel(); if (lockInputFile) { inLock = in.tryLock(0, Long.MAX_VALUE, true); if (null == inLock) { throw new IOException("Unable to obtain shared file lock for: " + source.getAbsolutePath()); } } if (lockOutputFile) { outLock = out.tryLock(0, Long.MAX_VALUE, false); if (null == outLock) { throw new IOException( "Unable to obtain exclusive file lock for: " + destination.getAbsolutePath()); } } long bytesWritten = 0; do { bytesWritten += out.transferFrom(in, bytesWritten, TRANSFER_CHUNK_SIZE_BYTES); fileSize = in.size(); } while (bytesWritten < fileSize); out.force(false); FileUtils.closeQuietly(fos); FileUtils.closeQuietly(fis); fos = null; fis = null; if (move && !FileUtils.deleteFile(source, null, 5)) { if (logger == null) { FileUtils.deleteFile(destination, null, 5); throw new IOException("Could not remove file " + source.getAbsolutePath()); } else { logger.warn( "Configured to delete source file when renaming/move not successful. However, unable to delete file at: " + source.getAbsolutePath()); } } } finally { FileUtils.releaseQuietly(inLock); FileUtils.releaseQuietly(outLock); FileUtils.closeQuietly(fos); FileUtils.closeQuietly(fis); } } return fileSize; }
From source file:com.almunt.jgcaap.systemupdater.DownloadService.java
public void copy(File src, File dst) throws IOException { FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst); FileChannel inChannel = inStream.getChannel(); FileChannel outChannel = outStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inStream.close();/* ww w .j av a 2 s. com*/ outStream.close(); }
From source file:de.Keyle.MyPet.util.Updater.java
public void download() { String url = "https://mypet-plugin.de/download/" + plugin + "/"; if (MyPetVersion.isDevBuild()) { url += "dev"; } else {//from w w w . ja v a2s . c om url += "release"; } File pluginFile; if (Configuration.Update.REPLACE_OLD) { pluginFile = new File(MyPetApi.getPlugin().getFile().getParentFile().getAbsolutePath(), "update/" + MyPetApi.getPlugin().getFile().getName()); } else { pluginFile = new File(MyPetApi.getPlugin().getFile().getParentFile().getAbsolutePath(), "update/MyPet-" + latest.getVersion() + ".jar"); } String finalUrl = url; thread = new Thread(() -> { try { MyPetApi.getLogger().info(ChatColor.RED + "Start update download: " + ChatColor.RESET + latest); URL website = new URL(finalUrl); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(pluginFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); String message = "Finished update download."; if (Configuration.Update.REPLACE_OLD || MyPetApi.getPlugin().getFile().getName() .equals("MyPet-" + latest.getVersion() + ".jar")) { message += " The update will be loaded on the next server start."; } else { message += " The file was stored in the \"update\" folder."; } MyPetApi.getLogger().info(message); } catch (IOException e) { e.printStackTrace(); } }); thread.start(); }
From source file:updater.UpdaterGUI.java
@SuppressWarnings("resource") public UpdaterGUI() { try {//from w w w .ja v a2 s . com URL url1 = new URL( "https://raw.githubusercontent.com/kvsjxd/Droid-PC-Suite/master/.release-version.txt"); ReadableByteChannel obj1 = Channels.newChannel(url1.openStream()); FileOutputStream outputstream1 = new FileOutputStream(".release-version.txt"); outputstream1.getChannel().transferFrom(obj1, 0, Long.MAX_VALUE); URL url2 = new URL( "https://raw.githubusercontent.com/kvsjxd/Droid-PC-Suite/master/.release-changelog.txt"); ReadableByteChannel obj2 = Channels.newChannel(url2.openStream()); FileOutputStream outputstream2 = new FileOutputStream(".release-changelog.txt"); outputstream2.getChannel().transferFrom(obj2, 0, Long.MAX_VALUE); FileReader file = new FileReader(".release-version.txt"); BufferedReader reader = new BufferedReader(file); String DownloadedString = reader.readLine(); File file2 = new File(".release-version.txt"); if (file2.exists() && !file2.isDirectory()) { file2.delete(); } AvailableUpdate = Double.parseDouble(DownloadedString); InputStreamReader reader2 = new InputStreamReader( getClass().getResourceAsStream("/others/app-version.txt")); String tmp = IOUtils.toString(reader2); ApplicationVersion = Double.parseDouble(tmp); } catch (Exception e) { e.printStackTrace(); } setIconImage(Toolkit.getDefaultToolkit().getImage(UpdaterGUI.class.getResource("/graphics/Icon.png"))); setResizable(false); setType(Type.UTILITY); setTitle("Updater"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 430, 415); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblApplicationVersion = new JLabel("App Version: v" + ApplicationVersion); lblApplicationVersion.setBounds(12, 12, 222, 15); contentPane.add(lblApplicationVersion); JLabel lblUpdateVersion = new JLabel("Update Version: v" + AvailableUpdate); lblUpdateVersion.setBounds(12, 30, 222, 15); contentPane.add(lblUpdateVersion); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(0, 51, 422, 281); contentPane.add(scrollPane); JTextArea UpdateChangelogViewer = new JTextArea(); scrollPane.setViewportView(UpdateChangelogViewer); JButton btnDownload = new JButton("Download"); btnDownload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFrame parentFrame = new JFrame(); JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Zip Files", "zip"); fileChooser.setFileFilter(filter); fileChooser.setDialogTitle("Save as"); int userSelection = fileChooser.showSaveDialog(parentFrame); if (userSelection == JFileChooser.APPROVE_OPTION) { File fileToSave = fileChooser.getSelectedFile(); try { URL url = new URL("https://github.com/kvsjxd/Droid-PC-Suite/releases/download/" + AvailableUpdate + "/DPCS.v" + AvailableUpdate + ".Stable.zip"); ReadableByteChannel obj = Channels.newChannel(url.openStream()); FileOutputStream outputstream = new FileOutputStream(fileToSave.getAbsolutePath() + ".zip"); outputstream.getChannel().transferFrom(obj, 0, Long.MAX_VALUE); JOptionPane.showMessageDialog(null, "Download complete!\nPlease delete this version and extract the downloaded zip\nwhich is saved at " + fileToSave.getAbsolutePath() + ".zip"); } catch (Exception e) { e.printStackTrace(); } } } }); btnDownload.setBounds(140, 344, 117, 25); contentPane.add(btnDownload); try { FileReader reader3 = new FileReader(new File(".release-changelog.txt")); UpdateChangelogViewer.read(reader3, ""); File file3 = new File(".release-changelog.txt"); if (file3.exists() && !file3.isDirectory()) { file3.delete(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.commonsware.android.qrck.SyncService.java
@SuppressWarnings("unchecked") @Override// w w w .ja v a 2 s. c om protected void onHandleIntent(Intent intent) { ArrayList<String> visited = new ArrayList<String>(); if (network.isNetworkAvailable()) { inProgress.set(true); broadcastStatus(); try { URL jsonUrl = new URL(SYNC_URL); ReadableByteChannel rbc = Channels.newChannel(jsonUrl.openStream()); FileOutputStream fos = openFileOutput(SYNC_LOCAL_FILE, 0); fos.getChannel().transferFrom(rbc, 0, 1 << 16); JSONObject json = AppUtils.load(this, SYNC_LOCAL_FILE); for (Iterator<String> i = json.keys(); i.hasNext();) { String title = i.next(); String url = json.getString(title); Entry entry = new Entry(title, url); String filename = entry.getFilename(); File imageFile = new File(getFilesDir(), filename); if (!imageFile.exists()) { visited.add(filename); URL imageUrl = new URL(jsonUrl, entry.getUrl()); rbc = Channels.newChannel(imageUrl.openStream()); fos = new FileOutputStream(imageFile); fos.getChannel().transferFrom(rbc, 0, 1 << 16); } } String[] children = getFilesDir().list(); if (children != null) { for (int i = 0; i < children.length; i++) { String filename = children[i]; if (!SYNC_LOCAL_FILE.equals(filename) && !visited.contains(filename)) { new File(getFilesDir(), filename).delete(); } } } } catch (Exception ex) { // TODO: let the UI know about this via broadcast Log.e(TAG, "Exception syncing", ex); AppUtils.cleanup(this); } finally { inProgress.set(false); broadcastStatus(); syncCompleted(); } } }