public void publicizeResources(File arscFile) throws AndrolibException { byte[] data = new byte[(int) arscFile.length()]; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(arscFile); in.read(data); publicizeResources(data); out = new FileOutputStream(arscFile); out.write(data); } catch (IOException ex) { throw new AndrolibException(ex); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } if (out != null) { try { out.close(); } catch (IOException ex) { } } } }
/** * Load a system library from a stream. Copies the library to a temp file and loads from there. * * @param libname name of the library (just used in constructing the library name) * @param is InputStream pointing to the library */ private void loadLibraryFromStream(String libname, InputStream is) { try { File tempfile = createTempFile(libname); OutputStream os = new FileOutputStream(tempfile); logger.debug("tempfile.getPath() = " + tempfile.getPath()); long savedTime = System.currentTimeMillis(); // Leo says 8k block size is STANDARD ;) byte buf[] = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); InputStream lock = new FileInputStream(tempfile); os.close(); double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3; logger.debug("Copying took " + seconds + " seconds."); logger.debug("Loading library from " + tempfile.getPath() + "."); System.load(tempfile.getPath()); lock.close(); } catch (IOException io) { logger.error("Could not create the temp file: " + io.toString() + ".\n"); } catch (UnsatisfiedLinkError ule) { logger.error("Couldn't load copied link file: " + ule.toString() + ".\n"); throw ule; } }
/** * Decode Base64 encoded data from one file to the other. Characters in the Base64 alphabet, white * space and equals sign are expected to be in urlencoded data. The presence of other characters * could be a sign that the data is corrupted. * * @param fIn File to be decoded. * @param fOut File to which the results should be written (may be the same as fIn). * @param throwExceptions Whether to throw exceptions when unexpected data is encountered. * @throws IOException if an IO error occurs. * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is * specified. * @since ostermillerutils 1.00.00 */ public static void decode(File fIn, File fOut, boolean throwExceptions) throws IOException { File temp = null; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(fIn)); temp = File.createTempFile("Base64", null, null); out = new BufferedOutputStream(new FileOutputStream(temp)); decode(in, out, throwExceptions); in.close(); in = null; out.flush(); out.close(); out = null; FileHelper.move(temp, fOut, true); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { if (throwExceptions) throw ignore; } in = null; } if (out != null) { try { out.flush(); out.close(); } catch (IOException ignore) { if (throwExceptions) throw ignore; } out = null; } } }
public void run() { try { gatewaySocket = sslFactory.createServerSocket(gatewayPort); } catch (IOException e) { messages.release(); throw new RuntimeException(e); } InputStream in = null; OutputStream out = null; try { // Listen for connections startUp.release(); Socket socket = gatewaySocket.accept(); // Create streams to securely send and receive data to the client in = socket.getInputStream(); out = socket.getOutputStream(); // Read from in and write to out... byte[] read = readFully(in); received.write(read); messages.release(); // Close the socket in.close(); out.close(); } catch(Throwable e) { try { in.close(); } catch (Exception _) {} try { out.close(); } catch (Exception _) {} messages.release(); } }
private static void writeFile( ByteCodeClass cls, File outputDir, ConcatenatingFileOutputStream writeBufferInstead) throws Exception { OutputStream outMain = writeBufferInstead != null && ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS ? writeBufferInstead : new FileOutputStream( new File( outputDir, cls.getClsName() + "." + ByteCodeTranslator.output.extension())); if (outMain instanceof ConcatenatingFileOutputStream) { ((ConcatenatingFileOutputStream) outMain).beginNextFile(cls.getClsName()); } if (ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS) { outMain.write(cls.generateCCode(classes).getBytes()); outMain.close(); // we also need to write the header file for iOS String headerName = cls.getClsName() + ".h"; FileOutputStream outHeader = new FileOutputStream(new File(outputDir, headerName)); outHeader.write(cls.generateCHeader().getBytes()); outHeader.close(); } else { outMain.write(cls.generateCSharpCode().getBytes()); outMain.close(); } }
@BeforeTest(alwaysRun = true) public void setUp() throws Exception { SecureRandom.getInstance("SHA1PRNG").nextBytes(nonEncodableBytesToWrite); String phrase = "all work and no play make Jack a dull boy"; byte[] bytes = phrase.getBytes(); int cursor = 0; while (cursor <= bytesToWrite.length) { System.arraycopy( bytes, 0, bytesToWrite, cursor, (bytes.length + cursor < bytesToWrite.length) ? bytes.length : bytesToWrite.length - cursor); cursor += bytes.length; } ByteArrayOutputStream nonCompressed = new ByteArrayOutputStream(); OutputStream os = new LZFOutputStream(nonCompressed); os.write(nonEncodableBytesToWrite); os.close(); nonCompressableBytes = nonCompressed.toByteArray(); ByteArrayOutputStream compressed = new ByteArrayOutputStream(); os = new LZFOutputStream(compressed); os.write(bytesToWrite); os.close(); compressedBytes = compressed.toByteArray(); }
@SuppressWarnings("resource") private PostMain(String url, String file, String tempDir) throws IOException { FileInputStream fio = new FileInputStream(file); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "text/xml"); connection.addRequestProperty("SOAPAction", "\"\""); OutputStream out = connection.getOutputStream(); int ch; try { while ((ch = fio.read()) != -1) { out.write((char) ch); } } finally { fio.close(); out.close(); } InputStream io; boolean failed = false; try { io = connection.getInputStream(); System.out.println("SUCCESS:"); } catch (IOException e) { System.out.println("FAILED:"); io = connection.getErrorStream(); failed = true; } OutputStream fout; if (tempDir != null) { File f = File.createTempFile("result", "" + failed, new File("temp")); fout = new FileOutputStream(f); } else { fout = System.out; } try { StringBuffer sb = new StringBuffer(); while ((ch = io.read()) != -1) { sb.append((char) ch); } boolean dumpResponse = false; if (failed || dumpResponse) { fout.write(sb.toString().getBytes()); } } finally { fout.close(); io.close(); } }
// -creatediff -applydiff -debug -output file public static void main(String[] args) throws IOException { boolean diff = true; boolean minimal = true; String outputFile = "out.jardiff"; for (int counter = 0; counter < args.length; counter++) { // for backward compatibilty with 1.0.1/1.0 if (args[counter].equals("-nonminimal") || args[counter].equals("-n")) { minimal = false; } else if (args[counter].equals("-creatediff") || args[counter].equals("-c")) { diff = true; } else if (args[counter].equals("-applydiff") || args[counter].equals("-a")) { diff = false; } else if (args[counter].equals("-debug") || args[counter].equals("-d")) { _debug = true; } else if (args[counter].equals("-output") || args[counter].equals("-o")) { if (++counter < args.length) { outputFile = args[counter]; } } else if (args[counter].equals("-applydiff") || args[counter].equals("-a")) { diff = false; } else { if ((counter + 2) != args.length) { showHelp(); System.exit(0); } if (diff) { try { OutputStream os = new FileOutputStream(outputFile); JarDiff.createPatch(args[counter], args[counter + 1], os, minimal); os.close(); } catch (IOException ioe) { try { System.out.println(getResources().getString("jardiff.error.create") + " " + ioe); } catch (MissingResourceException mre) { } } } else { try { OutputStream os = new FileOutputStream(outputFile); new JarDiffPatcher().applyPatch(null, args[counter], args[counter + 1], os); os.close(); } catch (IOException ioe) { try { System.out.println(getResources().getString("jardiff.error.apply") + " " + ioe); } catch (MissingResourceException mre) { } } } System.exit(0); } } showHelp(); }
public void write(SecureItemTable tbl, char[] password) throws IOException { OutputStream os = new FileOutputStream(file); OutputStream xmlout; if (password.length == 0) { xmlout = os; os = null; } else { PBEKeySpec keyspec = new PBEKeySpec(password); Cipher c; try { SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = fac.generateSecret(keyspec); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.ENCRYPT_MODE, key, pbeSpec); } catch (java.security.GeneralSecurityException exc) { os.close(); IOException ioe = new IOException("Security exception during write"); ioe.initCause(exc); throw ioe; } CipherOutputStream out = new CipherOutputStream(os, c); xmlout = out; } try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource src = new DOMSource(tbl.getDocument()); StringWriter writer = new StringWriter(); StreamResult sr = new StreamResult(writer); t.transform(src, sr); OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8); osw.write(writer.toString()); osw.close(); } catch (Exception exc) { IOException ioe = new IOException("Unable to serialize XML"); ioe.initCause(exc); throw ioe; } finally { xmlout.close(); if (os != null) os.close(); } tbl.setDirty(false); return; }
@Override public void destroy() { try { in.close(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } try { err.close(); } catch (IOException e) { } }
@Override public InputStream sendXmlRpc(byte[] request) throws IOException { // Create a trust manager that does not validate certificate for this connection TrustManager[] trustAllCerts = new TrustManager[] {new PyPITrustManager()}; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new SecureRandom()); final HttpConfigurable settings = HttpConfigurable.getInstance(); con = settings.openConnection(PYPI_LIST_URL); if (con instanceof HttpsURLConnection) { ((HttpsURLConnection) con).setSSLSocketFactory(sslContext.getSocketFactory()); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); return con.getInputStream(); } catch (NoSuchAlgorithmException e) { LOG.warn(e.getMessage()); } catch (KeyManagementException e) { LOG.warn(e.getMessage()); } return super.sendXmlRpc(request); }
public void close() { if (closed) { return; } closed = true; /* close the underlying connection if, * a) the streams not set up yet, no response can be sent, or * b) if the wrapper output stream is not set up, or * c) if the close of the input/outpu stream fails */ try { if (uis_orig == null || uos == null) { connection.close(); return; } if (!uos_orig.isWrapped()) { connection.close(); return; } if (!uis_orig.isClosed()) { uis_orig.close(); } uos.close(); } catch (IOException e) { connection.close(); } }
/** * close buffered output stream * * @throws WriterException - if can`t close stream */ public void close() throws WriterException { try { bufferedStream.close(); } catch (IOException e) { throw new WriterException(e); } }
public static void save(Properties properties, File file) throws IOException { Assert.notNull(properties, "存储的属性为空!"); OutputStream outputStream = new FileOutputStream(file); properties.store(outputStream, "saved on " + DateHelper.getStringDate()); outputStream.flush(); outputStream.close(); }
void out_close() { try { if (out != null && !out_dontclose) out.close(); out = null; } catch (Exception ee) { } }
private static void writeTokenToFile(String file, TBase token) { if (file != null && file.equals("stdout")) { System.out.println(token); } else { OutputStream os = null; try { os = new FileOutputStream(new File(file)); os.write(new TSerializer().serialize(token)); } catch (FileNotFoundException e) { System.err.println("Output file not found: " + file + " error: " + e.getMessage()); } catch (IOException e) { System.err.println("Error writing to output file: " + file + " error: " + e.getMessage()); } catch (TException e) { System.err.println("Unable to serialize token to file: " + e.getMessage()); } finally { if (os != null) { try { os.close(); } catch (IOException e) { // ignore } } } } }
private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput("values/public.xml"); serial.setOutput(outStream, null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResSpec spec : pkg.listResSpecs()) { serial.startTag(null, "public"); serial.attribute(null, "type", spec.getType().getName()); serial.attribute(null, "name", spec.getName()); serial.attribute(null, "id", String.format("0x%08x", spec.getId().id)); serial.endTag(null, "public"); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException ex) { throw new AndrolibException("Could not generate public.xml file", ex); } catch (DirectoryException ex) { throw new AndrolibException("Could not generate public.xml file", ex); } }
public static void main(String[] args) { try { Socket s1 = new Socket("127.0.0.1", 57643); InputStream is = s1.getInputStream(); DataInputStream dis = new DataInputStream(is); System.out.println(dis.readUTF()); OutputStream os = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF("Oh my gosh..."); dis.close(); is.close(); dos.close(); os.close(); s1.close(); } catch (ConnectException connExc) { connExc.printStackTrace(); System.out.println("Server connection failed"); } catch (IOException ioExc) { ioExc.printStackTrace(); } }
public static void copyFile(String filenameIn, String filenameOut, boolean buffer) throws IOException { long lenIn = new File(filenameIn).length(); if (debug) System.out.println("read " + filenameIn + " len = " + lenIn); InputStream in = new FileInputStream(filenameIn); if (buffer) new BufferedInputStream(in, 10000); OutputStream out = new FileOutputStream(filenameOut); if (buffer) out = new BufferedOutputStream(out, 1000); long start = System.currentTimeMillis(); IO.copyB(in, out, 10000); out.flush(); double took = .001 * (System.currentTimeMillis() - start); out.close(); in.close(); long lenOut = new File(filenameOut).length(); if (debug) System.out.println(" write file= " + filenameOut + " len = " + lenOut); double rate = lenIn / took / (1000 * 1000); String name = buffer ? "buffer" : "no buffer"; System.out.println(" copy (" + name + ") took = " + took + " sec; rate = " + rate + "Mb/sec"); }
public static void main(String[] args) { try { File fileName = File.createTempFile("d:/1.txt", null); OutputStream outputStream = new FileOutputStream(fileName); InputStream inputStream = new FileInputStream(fileName); ClassWithStatic classWithStatic = new ClassWithStatic(); classWithStatic.i = 3; classWithStatic.j = 4; classWithStatic.save(outputStream); outputStream.flush(); ClassWithStatic loadedObject = new ClassWithStatic(); ClassWithStatic.staticString = "something"; loadedObject.i = 6; loadedObject.j = 7; loadedObject.load(inputStream); System.out.println(ClassWithStatic.staticString); outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("Oops, something wrong with my file"); } catch (Exception e) { e.printStackTrace(); System.out.println("Oops, something wrong with save/load method"); } }
private void downloadInternal(URI address, File destination) throws Exception { OutputStream out = null; URLConnection conn; InputStream in = null; try { URL url = address.toURL(); out = new BufferedOutputStream(new FileOutputStream(destination)); conn = url.openConnection(); final String userAgentValue = calculateUserAgent(); conn.setRequestProperty("User-Agent", userAgentValue); in = conn.getInputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int numRead; long progressCounter = 0; while ((numRead = in.read(buffer)) != -1) { progressCounter += numRead; if (progressCounter / PROGRESS_CHUNK > 0) { System.out.print("."); progressCounter = progressCounter - PROGRESS_CHUNK; } out.write(buffer, 0, numRead); } } finally { System.out.println(""); if (in != null) { in.close(); } if (out != null) { out.close(); } } }
public static void write(String path, String content) { String s1 = new String(); try { File f = new File(path); if (f.exists()) { System.out.println("文件存在"); } else { System.out.println("文件不存在,正在创建...."); if (f.createNewFile()) { System.out.println("文件创建成功!"); } else { System.out.println("文件创建失败!"); } } s1 = "\n" + content; OutputStream outPut = new FileOutputStream(path, true); byte[] b = s1.getBytes(); outPut.write(b, 0, b.length); outPut.close(); } catch (Exception e) { e.printStackTrace(); } }
public Server() { try { ServerSocket ss = new ServerSocket(SERVER_PORT); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream out = s.getOutputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String sss = br.readLine(); System.out.println(sss); PrintWriter pw = new PrintWriter(out); pw.print("hello,我是服务器。"); pw.close(); br.close(); isr.close(); out.close(); is.close(); s.close(); ss.close(); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (IOException oe) { oe.printStackTrace(); } }
private static void moveVoicemail(String strContact, String strID, String strTempVMTS) { System.out.println(strContact + " " + strID + " " + strTempVMTS); try { File fSrc = new File(strSrcVMDir + "/" + strID + ".amr"); File fDest = new File(strDestVMDir + strContact + "/" + strTempVMTS + ".amr"); InputStream isSrc = new FileInputStream(fSrc); OutputStream osDest = new FileOutputStream(fDest); byte[] buf = new byte[1024]; int len; while ((len = isSrc.read(buf)) > 0) { osDest.write(buf, 0, len); } isSrc.close(); osDest.close(); System.out.println("File copied."); } catch (Exception e) { System.err.println(e.getLocalizedMessage()); System.err.println(); System.err.println(e.getStackTrace()); System.exit(0); } }
public static Reader communicate(final String urlStr, final CharSequence toSend) { OutputStream outputStream = null; try { final URL url = new URL(urlStr); final URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); outputStream = urlConnection.getOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(outputStream, DEFAULT_CHARSET.name()); writer.append(toSend); writer.close(); return new InputStreamReader(urlConnection.getInputStream(), DEFAULT_CHARSET.name()); } catch (IOException e) { LOG.warn("exception caught", e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { LOG.warn("exception caught", e); } } } return null; }
/** * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file. * * @param f The jar file to extract from. * @return a temporary file to which the plugin.xml file has been copied. */ public static File unpackPluginXML(File f) { InputStream in = null; OutputStream out = null; try { JarFile jar = new JarFile(f); ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE); if (entry == null) { return null; } File dest = File.createTempFile("jabref_plugin", ".xml"); dest.deleteOnExit(); in = new BufferedInputStream(jar.getInputStream(entry)); out = new BufferedOutputStream(new FileOutputStream(dest)); byte[] buffer = new byte[2048]; for (; ; ) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); return dest; } catch (IOException ex) { ex.printStackTrace(); return null; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
public static TByteArrayList transformByExternalCommand( final String command, final InputStream input) throws IOException { final Process process = Runtime.getRuntime().exec(command); final InputStream in = process.getInputStream(); final OutputStream out = process.getOutputStream(); final TByteArrayList bytes = new TByteArrayList(100500); final byte[] buffer = new byte[1024 * 1024]; try { int read; while ((read = input.read(buffer)) > 0) { out.write(buffer, 0, read); if (in.available() > 0) { read = in.read(buffer); bytes.add(buffer, 0, read); } } out.close(); while ((read = in.read(buffer)) > 0) { bytes.add(buffer, 0, read); } in.close(); } catch (IOException ioe) { System.err.println(readByteStream(process.getErrorStream())); LOG.error(ioe); throw ioe; } return bytes; }
private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name) throws IOException, FileNotFoundException { if (fileEntry == null) fileEntry = zip.getEntry(name); if (fileEntry == null) throw new FileNotFoundException("Can't find " + name + " in " + zip.getName()); File outFile = new File(sGREDir, name); if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize()) return false; File dir = outFile.getParentFile(); if (!dir.exists()) dir.mkdirs(); InputStream fileStream; fileStream = zip.getInputStream(fileEntry); OutputStream outStream = new FileOutputStream(outFile); while (fileStream.available() > 0) { int read = fileStream.read(buf, 0, buf.length); outStream.write(buf, 0, read); } fileStream.close(); outStream.close(); outFile.setLastModified(fileEntry.getTime()); return true; }
@Override public void run() { int count; try { while (!Thread.currentThread().isInterrupted() && !isComplete) { URL url = new URL(urlStr); URLConnection conection = url.openConnection(); conection.connect(); int lenghtOfFile = conection.getContentLength(); InputStream input = new BufferedInputStream(url.openStream(), 8192); File file = createNameFile( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + this.tile, type); OutputStream output = new FileOutputStream(file); byte data[] = new byte[1024]; long start = System.currentTimeMillis(); long total = 0; while ((count = input.read(data)) != -1) { total += count; output.write(data, 0, count); updateProgress((int) ((total * 100) / lenghtOfFile)); } output.flush(); output.close(); input.close(); isComplete = true; } } catch (Exception e) { isComplete = false; } }
private void generateValuesFile(ResValuesFile valuesFile, Directory out, ExtXmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput(valuesFile.getPath()); serial.setOutput((outStream), null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResource res : valuesFile.listResources()) { if (valuesFile.isSynthesized(res)) { continue; } ((ResValuesXmlSerializable) res.getValue()).serializeToResValuesXml(serial, res); } serial.endTag(null, "resources"); serial.newLine(); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException ex) { throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex); } catch (DirectoryException ex) { throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex); } }