List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:HttpGet.java
public static void main(String[] args) { SocketChannel server = null; // Channel for reading from server FileOutputStream outputStream = null; // Stream to destination file WritableByteChannel destination; // Channel to write to it try { // Exception handling and channel closing code follows this block // Parse the URL. Note we use the new java.net.URI, not URL here. URI uri = new URI(args[0]); // Now query and verify the various parts of the URI String scheme = uri.getScheme(); if (scheme == null || !scheme.equals("http")) throw new IllegalArgumentException("Must use 'http:' protocol"); String hostname = uri.getHost(); int port = uri.getPort(); if (port == -1) port = 80; // Use default port if none specified String path = uri.getRawPath(); if (path == null || path.length() == 0) path = "/"; String query = uri.getRawQuery(); query = (query == null) ? "" : '?' + query; // Combine the hostname and port into a single address object. // java.net.SocketAddress and InetSocketAddress are new in Java 1.4 SocketAddress serverAddress = new InetSocketAddress(hostname, port); // Open a SocketChannel to the server server = SocketChannel.open(serverAddress); // Put together the HTTP request we'll send to the server. String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request "Host: " + hostname + "\r\n" + // Required in HTTP 1.1 "Connection: close\r\n" + // Don't keep connection open "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank // line // indicates // end of // request // headers // Now wrap a CharBuffer around that request string CharBuffer requestChars = CharBuffer.wrap(request); // Get a Charset object to encode the char buffer into bytes Charset charset = Charset.forName("ISO-8859-1"); // Use the charset to encode the request into a byte buffer ByteBuffer requestBytes = charset.encode(requestChars); // Finally, we can send this HTTP request to the server. server.write(requestBytes);/*from www . jav a2 s . c o m*/ // Set up an output channel to send the output to. if (args.length > 1) { // Use a specified filename outputStream = new FileOutputStream(args[1]); destination = outputStream.getChannel(); } else // Or wrap a channel around standard out destination = Channels.newChannel(System.out); // Allocate a 32 Kilobyte byte buffer for reading the response. // Hopefully we'll get a low-level "direct" buffer ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024); // Have we discarded the HTTP response headers yet? boolean skippedHeaders = false; // The code sent by the server int responseCode = -1; // Now loop, reading data from the server channel and writing it // to the destination channel until the server indicates that it // has no more data. while (server.read(data) != -1) { // Read data, and check for end data.flip(); // Prepare to extract data from buffer // All HTTP reponses begin with a set of HTTP headers, which // we need to discard. The headers end with the string // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already // skipped them then do so now. if (!skippedHeaders) { // First, though, read the HTTP response code. // Assume that we get the complete first line of the // response when the first read() call returns. Assume also // that the first 9 bytes are the ASCII characters // "HTTP/1.1 ", and that the response code is the ASCII // characters in the following three bytes. if (responseCode == -1) { responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0') + 1 * (data.get(11) - '0'); // If there was an error, report it and quit // Note that we do not handle redirect responses. if (responseCode < 200 || responseCode >= 300) { System.err.println("HTTP Error: " + responseCode); System.exit(1); } } // Now skip the rest of the headers. try { for (;;) { if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13) && (data.get() == 10)) { skippedHeaders = true; break; } } } catch (BufferUnderflowException e) { // If we arrive here, it means we reached the end of // the buffer and didn't find the end of the headers. // There is a chance that the last 1, 2, or 3 bytes in // the buffer were the beginning of the \r\n\r\n // sequence, so back up a bit. data.position(data.position() - 3); // Now discard the headers we have read data.compact(); // And go read more data from the server. continue; } } // Write the data out; drain the buffer fully. while (data.hasRemaining()) destination.write(data); // Now that the buffer is drained, put it into fill mode // in preparation for reading more data into it. data.clear(); // data.compact() also works here } } catch (Exception e) { // Report any errors that arise System.err.println(e); System.err.println("Usage: java HttpGet <URL> [<filename>]"); } finally { // Close the channels and output file stream, if needed try { if (server != null && server.isOpen()) server.close(); if (outputStream != null) outputStream.close(); } catch (IOException e) { } } }
From source file:MainClass.java
private static void test() throws Exception { long[] primes = new long[] { 1, 2, 3, 5, 7 }; File aFile = new File("C:/test/primes.txt"); FileOutputStream outputFile = null; outputFile = new FileOutputStream(aFile); FileChannel file = outputFile.getChannel(); ByteBuffer[] buffers = new ByteBuffer[3]; buffers[0] = ByteBuffer.allocate(8); buffers[2] = ByteBuffer.allocate(8); String primeStr = null;// w w w .j a v a 2 s. com for (long prime : primes) { primeStr = "prime = " + prime; buffers[0].putDouble((double) primeStr.length()).flip(); buffers[1] = ByteBuffer.allocate(primeStr.length()); buffers[1].put(primeStr.getBytes()).flip(); buffers[2].putLong(prime).flip(); file.write(buffers); buffers[0].clear(); buffers[2].clear(); } System.out.println("File written is " + file.size() + "bytes."); outputFile.close(); }
From source file:MainClass.java
private static void createFile() throws Exception { long[] primes = new long[] { 1, 2, 3, 5, 7 }; File aFile = new File("C:/primes.bin"); FileOutputStream outputFile = new FileOutputStream(aFile); FileChannel file = outputFile.getChannel(); final int BUFFERSIZE = 100; ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE); LongBuffer longBuf = buf.asLongBuffer(); int primesWritten = 0; while (primesWritten < primes.length) { longBuf.put(primes, primesWritten, min(longBuf.capacity(), primes.length - primesWritten)); buf.limit(8 * longBuf.position()); file.write(buf);/*from w w w. j a v a2 s. c o m*/ primesWritten += longBuf.position(); longBuf.clear(); buf.clear(); } System.out.println("File written is " + file.size() + "bytes."); outputFile.close(); }
From source file:Main.java
public static void copyFileFast(FileInputStream is, FileOutputStream os) throws IOException { FileChannel in = is.getChannel(); FileChannel out = os.getChannel(); in.transferTo(0, in.size(), out);//from ww w. j av a2s .co m }
From source file:Main.java
public static 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 . ja v a2 s . c o m outStream.close(); }
From source file:Main.java
public static void copyFile(File src, File dst) throws IOException { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); try {//from ww w. j a v a 2 s .c om inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } outChannel.close(); } in.close(); out.close(); }
From source file:com.kurento.kmf.test.services.Recorder.java
public static float getPesqMos(String audio, int sampleRate) { float pesqmos = 0; try {/* w w w .j a v a 2 s.c om*/ String pesq = KurentoServicesTestHelper.getTestFilesPath() + "/bin/pesq/PESQ"; String origWav = ""; if (audio.startsWith(HTTP_TEST_FILES)) { origWav = KurentoServicesTestHelper.getTestFilesPath() + audio.replace(HTTP_TEST_FILES, ""); } else { // Download URL origWav = KurentoMediaServerManager.getWorkspace() + "/downloaded.wav"; URL url = new URL(audio); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(origWav); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } Shell.runAndWait(pesq, "+" + sampleRate, origWav, RECORDED_WAV); List<String> lines = FileUtils.readLines(new File(PESQ_RESULTS), "utf-8"); pesqmos = Float.parseFloat(lines.get(1).split("\t")[2].trim()); log.info("PESQMOS " + pesqmos); Shell.runAndWait("rm", PESQ_RESULTS); } catch (IOException e) { log.error("Exception recording local audio", e); } return pesqmos; }
From source file:org.phenotips.textanalysis.internal.BiolarkFileUtils.java
/** * Downloads file located at given url and saves it with given filename in the current directory. * * @param fileName Name under which the file will be saved locally * @param url URL of hte file//from w ww. j a v a 2 s . c o m * @return File which was downloaded * @throws IOException if downloading fails */ public static File downloadFile(String fileName, String url) throws IOException { final URL resourcesURL = new URL(url); final ReadableByteChannel rbc = Channels.newChannel(resourcesURL.openStream()); FileOutputStream fos = new FileOutputStream(fileName); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); return new File(fileName); }
From source file:org.neo4j.server.webdriver.WebdriverChromeDriver.java
private static ZipFile downloadFile(String fromUrl) { System.out.println("Downloading binary from " + fromUrl); try {/* ww w . jav a2s .c o m*/ URL zipUrl = new URL(fromUrl); ReadableByteChannel rbc = Channels.newChannel(zipUrl.openStream()); File localPath = new File(System.getProperty("java.io.tmpdir"), "chromedriver.zip"); FileOutputStream zipOutputStream = new FileOutputStream(localPath); zipOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24); return new ZipFile(localPath); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.kurento.test.utils.Ffmpeg.java
public static float getPesqMos(String audio, int sampleRate) { float pesqmos = 0; try {/*from w w w . j a va 2s. com*/ String pesq = KurentoTest.getTestFilesDiskPath() + "/bin/pesq/PESQ"; String origWav = ""; if (audio.startsWith(HTTP_TEST_FILES)) { origWav = KurentoTest.getTestFilesDiskPath() + audio.replace(HTTP_TEST_FILES, ""); } else { // Download URL origWav = KurentoTest.getDefaultOutputFile("downloaded.wav"); URL url = new URL(audio); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(origWav); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } Shell.runAndWait(pesq, "+" + sampleRate, origWav, RECORDED_WAV); List<String> lines = FileUtils.readLines(new File(PESQ_RESULTS), "utf-8"); pesqmos = Float.parseFloat(lines.get(1).split("\t")[2].trim()); log.debug("PESQMOS " + pesqmos); Shell.runAndWait("rm", PESQ_RESULTS); } catch (IOException e) { log.error("Exception recording local audio", e); } return pesqmos; }