Example usage for java.io FileOutputStream write

List of usage examples for java.io FileOutputStream write

Introduction

In this page you can find the example usage for java.io FileOutputStream write.

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this file output stream.

Usage

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

@SuppressWarnings("ResultOfMethodCallIgnored")
public static void saveKeyByIP(String ip_address, PublicKey publicKey) {
    km_log.i("Saving public key for " + ip_address);
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(publicKey.getEncoded());
    File pubFile = new File(installationPath + File.separator + ip_address + ".pub");

    km_log.i("Deleting old key if it exists.");
    if (pubFile.exists())
        pubFile.delete();/*from   ww w. j a va  2s  .  co m*/

    try {
        km_log.i(pubFile.createNewFile() ? "Creation of public key file successful."
                : "Creation of public key file failed!");

        FileOutputStream pubOut = new FileOutputStream(pubFile);
        pubOut.write(Base64.encodeBase64(pubSpec.getEncoded()));
        pubOut.flush();
        pubOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving public key for " + ip_address + "!");
        e.printStackTrace();
    }
}

From source file:Main.java

public static void getTelephonyManagerMethods(Context context) {
    String out;/*  w  w w.  j  ava  2 s.c  o m*/
    try {
        File dir = new File(String.valueOf(context.getFilesDir()));
        // create the file in which we will write the contents
        String fileName = "telephony.txt";
        File file = new File(dir, fileName);
        FileOutputStream os = new FileOutputStream(file);
        Class<?> c = Class.forName(GENERIC);
        Method[] cm = c.getDeclaredMethods();
        for (Method m : cm) {
            out = m.toString() + "\n";
            os.write(out.getBytes());
        }
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:in.cs654.chariot.ashva.AshvaProcessor.java

/**
 * This function takes in request, executes the request and returns the response.
 * The request is written into /tmp/<request_id>.req file. While running the docker container, /tmp dir is mounted
 * to /tmp of the container. This enables ease of data exchange. TODO encryption
 * Docker runs the request and puts the result into /tmp/<request_id>.res.
 * If the request specifies a timeout, it is picked up, else default timeout is set for the process to run
 * @param request containing function_name and other required information
 * @return response of the request/*from w w w .  j a  va  2s .  c om*/
 */
private static BasicResponse handleTaskProcessingRequest(BasicRequest request) {
    final String requestID = request.getRequestId();
    try {
        final byte[] serializedBytes = AvroUtils.requestToBytes(request);
        final FileOutputStream fos = new FileOutputStream("/tmp/" + requestID + ".req");
        fos.write(serializedBytes);
        fos.close();
        String timeoutString = request.getExtraData().get("chariot_timeout");
        Long timeout;
        if (timeoutString != null) {
            timeout = Long.parseLong(timeoutString);
        } else {
            timeout = PROCESS_DEFAULT_TIMEOUT;
        }

        final String dockerImage = Mongo.getDockerImage(request.getDeviceId());
        final String cmd = "docker run -v /tmp:/tmp " + dockerImage + " /bin/chariot " + requestID;
        final Process process = Runtime.getRuntime().exec(cmd);
        TimeoutProcess timeoutProcess = new TimeoutProcess(process);
        timeoutProcess.start();
        try {
            timeoutProcess.join(timeout); // milliseconds
            if (timeoutProcess.exit != null) {
                File file = new File("/tmp/" + requestID + ".res");
                byte[] bytes = FileUtils.readFileToByteArray(file);
                LOGGER.info("Response generated for request " + requestID);
                return AvroUtils.bytesToResponse(bytes);
            } else {
                LOGGER.severe("Timeout in generating response for request " + requestID);
                return ResponseFactory.getTimeoutErrorResponse(request);
            }
        } catch (InterruptedException ignore) {
            timeoutProcess.interrupt();
            Thread.currentThread().interrupt();
            LOGGER.severe("Error in generating response for request " + requestID);
            return ResponseFactory.getErrorResponse(request);
        } finally {
            process.destroy();
        }
    } catch (IOException ignore) {
        LOGGER.severe("Error in generating response for request: " + requestID);
        return ResponseFactory.getErrorResponse(request);
    }
}

From source file:Main.java

@SuppressLint("NewApi")
public static void getURL(String path) {
    String fileName = "";
    String dir = "/IndoorNavi/";
    File sdRoot = Environment.getExternalStorageDirectory();
    try {//w  w  w .  ja  va2  s . co  m
        // Open the URLConnection for reading
        URL u = new URL(path);
        // URL u = new URL("http://www.baidu.com/");
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();

        int code = uc.getResponseCode();
        String response = uc.getResponseMessage();
        //System.out.println("HTTP/1.x " + code + " " + response);
        for (int j = 1;; j++) {
            String key = uc.getHeaderFieldKey(j);
            String header = uc.getHeaderField(j);
            if (!(key == null)) {
                if (key.equals("Content-Name"))
                    fileName = header;
            }
            if (header == null || key == null)
                break;
            //System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
        }
        Log.i("zhr", fileName);
        //System.out.println();

        try (InputStream in = new BufferedInputStream(uc.getInputStream())) {

            // chain the InputStream to a Reader
            Reader r = new InputStreamReader(in);
            int c;
            File mapFile = new File(sdRoot, dir + fileName);
            mapFile.createNewFile();
            FileOutputStream filecon = new FileOutputStream(mapFile);
            while ((c = r.read()) != -1) {
                //System.out.print((char) c);
                filecon.write(c);
                filecon.flush();

            }
            filecon.close();
        }

    } catch (MalformedURLException ex) {
        System.err.println(path + " is not a parseable URL");
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:Main.java

public static boolean copyFile(InputStream inputStream, File target) {
    boolean result = false;
    if (target == null) {
        return result;
    }/*from   ww w  . j a va 2  s  .co  m*/

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(target);
        byte[] buffer = new byte[1024];
        while (inputStream.read(buffer) > 0) {
            fileOutputStream.write(buffer);
        }
        result = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
            }
        }
    }

    return result;
}

From source file:Main.java

public static boolean addFile(InputStream src, File dest) {
    try {// w  w  w.  j  a  va  2 s  .  c o m
        FileOutputStream out = new FileOutputStream(dest);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(src));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            out.write((line + "\n").getBytes());
        }

        out.close();
        bufferedReader.close();

        return true;
    } catch (IOException e) {
    }
    return false;
}

From source file:com.mpower.mintel.android.application.MIntel.java

private static void copyAudioFiles(String[] assetName) {
    for (int i = 0; i < assetName.length; i++) {
        File file = new File(METADATA_PATH, assetName[i]);
        if (!file.exists()) {
            AssetManager mngr = getAppContext().getAssets();
            ByteArrayBuffer baf = new ByteArrayBuffer(2048);
            try {
                InputStream path = mngr.open(assetName[i]);
                BufferedInputStream bis = new BufferedInputStream(path, 1024);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }/*www  .java  2s  .  com*/
                byte[] bitmapdata = baf.toByteArray();

                FileOutputStream fos;
                fos = new FileOutputStream(file);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:com.sap.nwcloudmanager.api.LogAPI.java

public static void downloadLog(final Context context, final String appId, final String logName,
        final DownloadLogResponseHandler downloadLogResponseHandler) {

    NetWeaverCloudConfig config = NetWeaverCloudConfig.getInstance();
    getHttpClient().setBasicAuth(config.getUsername(), config.getPassword());
    String[] contentTypes = { "application/x-gzip" };
    getHttpClient().get("https://monitoring." + config.getHost() + "/log/api_basic/logs/" + config.getAccount()
            + "/" + appId + "/web/" + logName, null, new BinaryHttpResponseHandler(contentTypes) {

                /*/*from  w  w w .  jav a 2  s.  c o  m*/
                 * (non-Javadoc)
                 * 
                 * @see
                 * com.loopj.android.http.BinaryHttpResponseHandler#onSuccess(byte
                 * [])
                 */
                @Override
                public void onSuccess(byte[] arg0) {

                    GZIPInputStream gzis = null;

                    try {
                        gzis = new GZIPInputStream(new ByteArrayInputStream(arg0));

                        StringBuilder string = new StringBuilder();
                        byte[] data = new byte[4028];
                        int bytesRead;
                        while ((bytesRead = gzis.read(data)) != -1) {
                            string.append(new String(data, 0, bytesRead));
                        }

                        File downloadsFile = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                        if (downloadsFile.exists()) {
                            downloadsFile = new File(
                                    context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                                            .getAbsolutePath() + "/" + logName);
                            FileOutputStream fos = new FileOutputStream(downloadsFile);
                            fos.write(string.toString().getBytes());
                            fos.close();
                        }

                        downloadLogResponseHandler.onSuccess(downloadsFile.getAbsolutePath());

                    } catch (IOException e) {
                        Log.e(e.getMessage());
                    } finally {
                        try {
                            if (gzis != null) {
                                gzis.close();
                            }
                        } catch (IOException e) {
                        }
                    }
                }

                @Override
                public void onFailure(Throwable arg0) {
                    downloadLogResponseHandler.onFailure(arg0, arg0.getMessage());
                }

            });
}

From source file:Main.java

public static void saveImage(Context context, String fileName, Bitmap bitmap, int quality) throws IOException {
    if (bitmap == null || fileName == null || context == null)
        return;//from w w w  .  j a  v  a2 s.co m

    FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, quality, stream);
    byte[] bytes = stream.toByteArray();
    fos.write(bytes);
    fos.close();
}

From source file:com.mirth.connect.server.util.FileUtil.java

/**
 * @deprecated/* w w  w.j a  v a  2s.  c  om*/
 * @see org.apache.commons.io.FileUtils#writeByteArrayToFile(File, byte[])
 * @param fileName
 * @param append
 * @param bytes
 * @throws IOException
 */
public static void write(String fileName, boolean append, byte[] bytes) throws IOException {
    File file = new File(fileName);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file, append);
        fos.write(bytes);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}