List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:com.recomdata.transmart.data.export.util.FileWriterUtil.java
public void writeFile(String url, File outputURLFile) { try {//w w w . ja v a 2 s . c o m URL celFileURL = new URL(url); ReadableByteChannel rbc = Channels.newChannel(celFileURL.openStream()); FileOutputStream fos = new FileOutputStream(outputURLFile); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } catch (MalformedURLException e) { log.info("Bad URL: " + url); } catch (IOException e) { log.info("IO Error:" + e.getMessage()); } }
From source file:org.loadosophia.client.LoadosophiaAPIClient.java
protected String[] multipartPost(LinkedList<Part> parts, String URL, int expectedSC) throws IOException { log.debug("Request POST: " + URL); parts.add(new StringPart("token", token)); PostMethod postRequest = new PostMethod(URL); MultipartRequestEntity multipartRequest = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postRequest.getParams());// www .ja va 2s.c o m postRequest.setRequestEntity(multipartRequest); int result = httpClient.executeMethod(postRequest); if (result != expectedSC) { String fname = File.createTempFile("error_", ".html").getAbsolutePath(); notifier.notifyAbout("Saving server error response to: " + fname); FileOutputStream fos = new FileOutputStream(fname); FileChannel resultFile = fos.getChannel(); resultFile.write(ByteBuffer.wrap(postRequest.getResponseBody())); resultFile.close(); throw new HttpException("Request returned not " + expectedSC + " status code: " + result); } byte[] bytes = postRequest.getResponseBody(); if (bytes == null) { bytes = new byte[0]; } String response = new String(bytes); return response.trim().split(";"); }
From source file:Main.java
public Main(String localPath, String remoteURL) { FileOutputStream fos; ReadableByteChannel rbc;//from ww w. j a v a 2 s. c o m URL url; try { url = new URL(remoteURL); rbc = new CallbackByteChannel(Channels.newChannel(url.openStream()), contentLength(url), this); fos = new FileOutputStream(localPath); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (Exception e) { e.printStackTrace(); } }
From source file:wicket.protocol.http.FilePageStore.java
/** * @see wicket.protocol.http.SecondLevelCacheSessionStore.IPageStore#storePage(java.lang.String, * wicket.Page)//from w ww .ja v a 2s.c o m */ public void storePage(String sessionId, Page page) { File sessionDir = new File(workDir, sessionId); sessionDir.mkdirs(); File pageFile = getPageFile(page.getNumericId(), page.getCurrentVersionNumber(), sessionDir); // TODO check can this be called everytime at this place? Putting should // be called after the rendering so it should be ok. page.internalDetach(); byte[] bytes = Objects.objectToByteArray(page); FileOutputStream fos = null; try { fos = new FileOutputStream(pageFile); ByteBuffer bb = ByteBuffer.wrap(bytes); fos.getChannel().write(bb); } catch (Exception e) { log.debug("Error saving page " + page.getId() + " with version " + page.getCurrentVersionNumber() + " for the sessionid " + sessionId + " from disc", e); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ex) { // ignore } } }
From source file:org.apache.solr.core.CoreContainer.java
/** Copies a src file to a dest file: * used to circumvent the platform discrepancies regarding renaming files. *//*from w w w .j a v a 2s .c om*/ public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); // do the file copy 32Mb at a time final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
From source file:org.apache.gobblin.example.githubjsontoparquet.EmbeddedGithubJsonToParquet.java
private void downloadFile(String fileUrl, Path destination) { if (destination.toFile().exists()) { Log.info(String.format("Skipping download for %s at %s because destination already exists", fileUrl, destination.toString())); return;/*from w ww.j a v a 2 s .co m*/ } try { URL archiveUrl = new URL(fileUrl); ReadableByteChannel rbc = Channels.newChannel(archiveUrl.openStream()); FileOutputStream fos = new FileOutputStream(String.valueOf(destination)); Log.info(String.format("Downloading %s at %s", fileUrl, destination.toString())); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); Log.info(String.format("Download complete for %s at %s", fileUrl, destination.toString())); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.red5.server.net.proxy.DebugProxyHandler.java
/** {@inheritDoc} */ @Override/*www . j a v a2s . c o m*/ public void sessionCreated(IoSession session) throws Exception { boolean isClient = session.getRemoteAddress().equals(forward); //session.getConfig(); if (log.isDebugEnabled()) { log.debug("Is downstream: " + isClient); session.setAttribute(ProtocolState.SESSION_KEY, new RTMP(isClient)); session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(codecFactory)); } session.getFilterChain().addFirst("proxy", new ProxyFilter(isClient ? "client" : "server")); if (true) { String fileName = System.currentTimeMillis() + '_' + forward.getHostName() + '_' + forward.getPort() + '_' + (isClient ? "DOWNSTREAM" : "UPSTREAM"); File headersFile = loader.getResource(dumpTo + fileName + ".cap").getFile(); headersFile.createNewFile(); File rawFile = loader.getResource(dumpTo + fileName + ".raw").getFile(); rawFile.createNewFile(); FileOutputStream headersFos = new FileOutputStream(headersFile); WritableByteChannel headers = headersFos.getChannel(); FileOutputStream rawFos = new FileOutputStream(rawFile); WritableByteChannel raw = rawFos.getChannel(); ByteBuffer header = ByteBuffer.allocate(1); header.put((byte) (isClient ? 0x00 : 0x01)); header.flip(); headers.write(header.buf()); session.getFilterChain().addFirst("dump", new NetworkDumpFilter(headers, raw)); } //session.getFilterChain().addLast( // "logger", new LoggingFilter() ); if (!isClient) { log.debug("Connecting.."); SocketConnector connector = new SocketConnector(); ConnectFuture future = connector.connect(forward, this); future.join(); // wait for connect, or timeout if (future.isConnected()) { if (log.isDebugEnabled()) { log.debug("Connected: " + forward); } IoSession client = future.getSession(); client.setAttribute(ProxyFilter.FORWARD_KEY, session); session.setAttribute(ProxyFilter.FORWARD_KEY, client); } } super.sessionCreated(session); }
From source file:com.mgmtp.perfload.perfalyzer.util.BinnedFilesMerger.java
public void mergeFiles() throws IOException { if (!inputDir.isDirectory()) { throw new IllegalArgumentException("The input File must be a directory"); }// w w w . ja v a2 s . c om StrTokenizer tokenizer = StrTokenizer.getCSVInstance(); tokenizer.setDelimiterChar(DELIMITER); Map<String, FileChannel> destChannels = newHashMap(); List<OutputStream> outputStreams = newArrayList(); File[] filesInInputDirectory = inputDir.listFiles(); try { for (File file : filesInInputDirectory) { FileInputStream fis = null; try { fis = new FileInputStream(file); for (Scanner scanner = new Scanner(fis.getChannel(), Charsets.UTF_8.name()); scanner .hasNext();) { String line = scanner.nextLine(); tokenizer.reset(line); List<String> tokenList = tokenizer.getTokenList(); String key = tokenList.get(sortCriteriaColumn); FileChannel destChannel = destChannels.get(key); if (destChannel == null) { FileOutputStream fos = new FileOutputStream( new File(outputDir, FILE_TYPE + "_" + key + ".out")); outputStreams.add(fos); destChannel = fos.getChannel(); destChannels.put(key, destChannel); //Write the Header...... Has to be improved IoUtilities.writeLineToChannel(destChannel, getHeader(), Charsets.UTF_8); } StrBuilder outputLine = new StrBuilder(); for (String s : tokenList) { StrBuilderUtils.appendEscapedAndQuoted(outputLine, DELIMITER, s); } IoUtilities.writeLineToChannel(destChannel, outputLine.toString(), Charsets.UTF_8); } } finally { closeQuietly(fis); } } } finally { outputStreams.forEach(IOUtils::closeQuietly); } }
From source file:org.apache.hama.bsp.message.io.WriteSpilledDataProcessor.java
private void initializeFileChannel() { FileOutputStream stream; try {/*ww w . j a va 2 s . c o m*/ stream = new FileOutputStream(new File(fileName), true); } catch (FileNotFoundException e) { LOG.error("Error opening file to write spilled data.", e); throw new RuntimeException(e); } fileChannel = stream.getChannel(); }
From source file:siddur.solidtrust.fault.FaultController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, @RequestParam("version") int v, Model model, HttpSession session) throws Exception { IFaultPersister persister = getPersister(v); //upload//from w w w . j a v a2 s. c o m log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }