Java Code Examples for java.io.FileOutputStream.write()

The following are Jave code examples for showing how to use write() of the java.io.FileOutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: BackendDrivenMenu   File: UrlCache.java   View Source Code Vote up 6 votes
private void downloadAndStore(String url, CacheEntry cacheEntry) throws IOException {
    Log.d(TAG, Thread.currentThread().getStackTrace()[2].getMethodName() + " " + hashCode());
    URL urlObj = new URL(url);
    URLConnection urlConnection = urlObj.openConnection();
    InputStream is = urlConnection.getInputStream();
    FileOutputStream fos = activity.openFileOutput(cacheEntry.fileName, Context.MODE_PRIVATE);

    int data = is.read();
    while (data != -1) {
        fos.write(data);
        data = is.read();
    }
    is.close();
    fos.close();
    Log.i(TAG, "Cache file '" + cacheEntry.fileName + "' successfully stored");
}
 
Example 2
Project: PaoMovie   File: CheapMP3.java   View Source Code Vote up 6 votes
public void WriteFile(File outputFile, int startFrame, int numFrames)
        throws java.io.IOException {
    outputFile.createNewFile();
    FileInputStream in = new FileInputStream(mInputFile);
    FileOutputStream out = new FileOutputStream(outputFile);
    int maxFrameLen = 0;
    for (int i = 0; i < numFrames; i++) {
        if (mFrameLens[startFrame + i] > maxFrameLen)
            maxFrameLen = mFrameLens[startFrame + i];
    }
    byte[] buffer = new byte[maxFrameLen];
    int pos = 0;
    for (int i = 0; i < numFrames; i++) {
        int skip = mFrameOffsets[startFrame + i] - pos;
        int len = mFrameLens[startFrame + i];
        if (skip > 0) {
            in.skip(skip);
            pos += skip;
        }
        in.read(buffer, 0, len);
        out.write(buffer, 0, len);
        pos += len;
    }
    in.close();
    out.close();
}
 
Example 3
Project: fdp2017   File: RemoveRepeated.java   View Source Code Vote up 6 votes
public void writeschema(String source, String destination){
        
try {
	File inFile = new File("data/myDB/"+source+"/schema.txt");
	File outFile = new File("data/myDB/"+destination+"/schema.txt");

	FileInputStream in = new FileInputStream(inFile);
	FileOutputStream out = new FileOutputStream(outFile);
	int c;
	while( (c = in.read() ) != -1)
		out.write(c);

	in.close();
	out.close();
} catch(IOException e) {
	e.printStackTrace();
}
  }
 
Example 4
Project: Auto.js   File: DownloadManager.java   View Source Code Vote up 6 votes
private void startImpl(ResponseBody body) throws IOException {
    byte[] buffer = new byte[4096];
    mFileOutputStream = new FileOutputStream(mPath);
    mInputStream = body.byteStream();
    long total = body.contentLength();
    long read = 0;
    while (true) {
        if (!mStatus.get()) {
            onCancel();
            return;
        }
        int len = mInputStream.read(buffer);
        if (len == -1) {
            break;
        }
        read += len;
        mFileOutputStream.write(buffer, 0, len);
        if (total > 0) {
            mProgress.onNext((int) (100 * read / total));
        }
    }
    mProgress.onComplete();
    recycle();
}
 
Example 5
Project: hadoop   File: TestSecureIOUtils.java   View Source Code Vote up 6 votes
@BeforeClass
public static void makeTestFile() throws Exception {
  Configuration conf = new Configuration();
  fs = FileSystem.getLocal(conf).getRaw();
  testFilePathIs =
      new File((new Path("target", TestSecureIOUtils.class.getSimpleName()
          + "1")).toUri().getRawPath());
  testFilePathRaf =
      new File((new Path("target", TestSecureIOUtils.class.getSimpleName()
          + "2")).toUri().getRawPath());
  testFilePathFadis =
      new File((new Path("target", TestSecureIOUtils.class.getSimpleName()
          + "3")).toUri().getRawPath());
  for (File f : new File[] { testFilePathIs, testFilePathRaf,
      testFilePathFadis }) {
    FileOutputStream fos = new FileOutputStream(f);
    fos.write("hello".getBytes("UTF-8"));
    fos.close();
  }

  FileStatus stat = fs.getFileStatus(
      new Path(testFilePathIs.toString()));
  // RealOwner and RealGroup would be same for all three files.
  realOwner = stat.getOwner();
  realGroup = stat.getGroup();
}
 
Example 6
Project: EyeShopping   File: Utils.java   View Source Code Vote up 6 votes
public static String exportResource(Context context, int resourceId, String dirname) {
    String fullname = context.getResources().getString(resourceId);
    String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
    try {
        InputStream is = context.getResources().openRawResource(resourceId);
        File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
        File resFile = new File(resDir, resName);

        FileOutputStream os = new FileOutputStream(resFile);

        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        is.close();
        os.close();

        return resFile.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CvException("Failed to export resource " + resName
                + ". Exception thrown: " + e);
    }
}
 
Example 7
Project: iosched-reader   File: MapUtils.java   View Source Code Vote up 6 votes
/**
 * Copy the file from the assets to the map tiles directory if it was
 * shipped with the APK.
 */
public static boolean copyTileAsset(Context context, String filename) {
    if (!hasTileAsset(context, filename)) {
        // file does not exist as asset
        return false;
    }

    // copy file from asset to internal storage
    try {
        InputStream is = context.getAssets().open(TILE_PATH + File.separator + filename);
        File f = getTileFile(context, filename);
        FileOutputStream os = new FileOutputStream(f);

        byte[] buffer = new byte[1024];
        int dataSize;
        while ((dataSize = is.read(buffer)) > 0) {
            os.write(buffer, 0, dataSize);
        }
        os.close();
    } catch (IOException e) {
        return false;
    }

    return true;
}
 
Example 8
Project: react-native-secure-key-store   File: Storage.java   View Source Code Vote up 5 votes
public static void writeValues(Context context, String filename, byte[] bytes) throws IOException {
    FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
    fos.write(bytes);
    fos.close();
}
 
Example 9
Project: ElectroLight-Penetration-Testing   File: BasicReverseShell.java   View Source Code Vote up 5 votes
public void export(File out) throws IOException {
	if (out.exists()) {
		throw new IOException("File " + out.getAbsolutePath() + " already exist.");
	}
	out.createNewFile();
	FileOutputStream outs = new FileOutputStream(out);
	outs.write(String.format(new TextFile("./payloads/BasicReverseShell.java").getText(), host, port).getBytes());
	outs.close();
	
}
 
Example 10
Project: ImageClassify   File: UnZipMainThread.java   View Source Code Vote up 5 votes
@Override
public void run() {
    super.run();
    try {
        listener.zipStart();
        long sumLength = 0;
        // 获取解压之后文件的大小,用来计算解压的进度
        long ziplength = getZipTrueSize(zipFileString);
        FileInputStream inputStream = new FileInputStream(zipFileString);
        ZipInputStream inZip = new ZipInputStream(inputStream);
        ZipEntry zipEntry;
        String szName = "";
        while ((zipEntry = inZip.getNextEntry()) != null) {
            szName = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                szName = szName.substring(0, szName.length() - 1);
                File folder = new File(outPathString + File.separator + szName);
                folder.mkdirs();
            } else {
                File file = new File(outPathString + File.separator + szName);
                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = inZip.read(buffer)) != -1) {
                    sumLength += len;
                    int progress = (int) ((sumLength * 100) / ziplength);
                    updateProgress(progress, listener);
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.close();
            }
        }
        listener.zipSuccess();
        inZip.close();
    } catch (Exception e) {
        listener.zipFail();
    }
}
 
Example 11
Project: quickhybrid-android   File: FileUtil.java   View Source Code Vote up 5 votes
/**
 * 从assets拷贝文件到文件夹
 *
 * @param con
 * @param assfilename
 * @param destpathname
 * @throws java.io.IOException
 */
public static void copyFileFromAss2Dir(Context con, String assfilename, String destpathname) throws IOException {
    InputStream fis = con.getResources().getAssets().open(assfilename);
    FileOutputStream fos = new FileOutputStream(destpathname);
    byte data[] = new byte[1024];
    int count;
    while ((count = fis.read(data)) != -1) {
        fos.write(data, 0, count);
    }
    fos.flush();
    fos.close();
    fis.close();
}
 
Example 12
Project: HybridForAndroid   File: HttpUtils.java   View Source Code Vote up 5 votes
/**
 *
 * @param urlPath url
 * @param filePath 文件全路径
 * @param callback 回调
 * @throws Exception
 */
public static void downloadFile(String urlPath, String filePath, HttpCallback callback) throws Exception {
    // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
    if (Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState())) {
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        // 获取到文件的大小
        int maxLength =conn.getContentLength();
        InputStream is = conn.getInputStream();
        File file = new File(filePath);
        // 目录不存在创建目录
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(file);
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[1024];
        int len;
        int progress = 0;
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
            progress += len;
            // 获取当前下载量
            callback.progress(progress,maxLength,filePath);
        }

        fos.close();
        bis.close();
        is.close();
    } else {
        throw new IOException("未发现有SD卡");
    }
}
 
Example 13
Project: AndroidWifiAutoLogin   File: WifiConfig.java   View Source Code Vote up 5 votes
static void saveWifiConfig(WifiConfig wifiConfig, File file) {
    try {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(wifiConfig.toJSONString().getBytes());
        fos.close();

        if(file.exists())
            Log.i(LOG_TAG,wifiConfig.getSsid()+" Config written.");
        else
            Log.i(LOG_TAG,wifiConfig.getSsid()+" Config not written.");
    }
    catch (Exception ex){
        Log.e(LOG_TAG, ex.getMessage());
    }
}
 
Example 14
Project: PaoMovie   File: CheapAMR.java   View Source Code Vote up 5 votes
public void WriteFile(File outputFile, int startFrame, int numFrames)
        throws java.io.IOException {
    outputFile.createNewFile();
    FileInputStream in = new FileInputStream(mInputFile);
    FileOutputStream out = new FileOutputStream(outputFile);

    byte[] header = new byte[6];
    header[0] = '#';
    header[1] = '!';
    header[2] = 'A';
    header[3] = 'M';
    header[4] = 'R';
    header[5] = '\n';
    out.write(header, 0, 6);

    int maxFrameLen = 0;
    for (int i = 0; i < numFrames; i++) {
        if (mFrameLens[startFrame + i] > maxFrameLen)
            maxFrameLen = mFrameLens[startFrame + i];
    }
    byte[] buffer = new byte[maxFrameLen];
    int pos = 0;
    for (int i = 0; i < numFrames; i++) {
        int skip = mFrameOffsets[startFrame + i] - pos;
        int len = mFrameLens[startFrame + i];
        if (skip < 0) {
            continue;
        }
        if (skip > 0) {
            in.skip(skip);
            pos += skip;
        }
        in.read(buffer, 0, len);
        out.write(buffer, 0, len);
        pos += len;
    }

    in.close();
    out.close();
}
 
Example 15
Project: AlphaLibary   File: Util.java   View Source Code Vote up 4 votes
public static void unzip(String zipPath, String outputFolder) {
    try {
        ZipFile zipFile = new ZipFile(zipPath);
        Enumeration<?> enu = zipFile.entries();

        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();

            String name = zipEntry.getName();

            File file = new File(outputFolder + File.separator + name);
            if (name.endsWith("/")) {
                file.mkdirs();
                continue;
            }

            File parent = file.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }

            InputStream is = zipFile.getInputStream(zipEntry);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = is.read(bytes)) >= 0) {
                fos.write(bytes, 0, length);
            }

            is.close();
            fos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 16
Project: hadoop   File: TestDFSUpgradeFromImage.java   View Source Code Vote up 4 votes
/**
 * Test that sets up a fake image from Hadoop 0.3.0 and tries to start a
 * NN, verifying that the correct error message is thrown.
 */
@Test
public void testFailOnPreUpgradeImage() throws IOException {
  Configuration conf = new HdfsConfiguration();

  File namenodeStorage = new File(TEST_ROOT_DIR, "nnimage-0.3.0");
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, namenodeStorage.toString());

  // Set up a fake NN storage that looks like an ancient Hadoop dir circa 0.3.0
  FileUtil.fullyDelete(namenodeStorage);
  assertTrue("Make " + namenodeStorage, namenodeStorage.mkdirs());
  File imageDir = new File(namenodeStorage, "image");
  assertTrue("Make " + imageDir, imageDir.mkdirs());

  // Hex dump of a formatted image from Hadoop 0.3.0
  File imageFile = new File(imageDir, "fsimage");
  byte[] imageBytes = StringUtils.hexStringToByte(
    "fffffffee17c0d2700000000");
  FileOutputStream fos = new FileOutputStream(imageFile);
  try {
    fos.write(imageBytes);
  } finally {
    fos.close();
  }

  // Now try to start an NN from it

  MiniDFSCluster cluster = null;
  try {
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
      .format(false)
      .manageDataDfsDirs(false)
      .manageNameDfsDirs(false)
      .startupOption(StartupOption.REGULAR)
      .build();
    fail("Was able to start NN from 0.3.0 image");
  } catch (IOException ioe) {
    if (!ioe.toString().contains("Old layout version is 'too old'")) {
      throw ioe;
    }
  } finally {
    // We expect startup to fail, but just in case it didn't, shutdown now.
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}
 
Example 17
Project: QuranAndroid   File: UnZipping.java   View Source Code Vote up 4 votes
@Override
protected Void doInBackground(String... params) {
    try {

        is = new FileInputStream(params[0] + "/" + params[1]);
        zis = new ZipInputStream(new BufferedInputStream(is));
        byte[] buffer = new byte[1024 * 3];
        int count;
        while ((ze = zis.getNextEntry()) != null) {
            filename = ze.getName();
            if (ze.isDirectory()) {
                File fmd = new File(params[0] + "/" + filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(params[0] + "/" + filename);
            int total = zis.available();
            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
                fileCount++;
                Intent zipedFiles = new Intent(AppConstants.Download.INTENT);
                zipedFiles.putExtra(AppConstants.Download.FILES, context.getString(R.string.extract) + " " + fileCount);
                zipedFiles.putExtra(AppConstants.Download.DOWNLOAD, AppConstants.Download.IN_EXTRACT);
                LocalBroadcastManager.getInstance(context).sendBroadcast(zipedFiles);
            }

            File zipFile = new File(params[0] + "/" + params[1]);
            zipFile.delete();

            if (zipFile.getAbsolutePath().contains("tafseer")) {
                copyFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + QuranApplication.getInstance()
                                .getString(R.string.app_folder_path) + "/tafaseer/" + params[1].replace(AppConstants.Extensions.ZIP, AppConstants.Extensions.SQLITE)),
                        new File(params[0] + "/" + params[1].replace(AppConstants.Extensions.ZIP, AppConstants.Extensions.SQLITE)));
            }

            fout.close();
            zis.closeEntry();
        }

        //send broadcast of success or failed
        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(AppConstants.Download.INTENT)
                .putExtra(AppConstants.Download.DOWNLOAD, AppConstants.Download.SUCCESS ));

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return null;
}
 
Example 18
Project: localcloud_fe   File: LocalFilesystem.java   View Source Code Vote up 4 votes
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
		int offset, boolean isBinary) throws IOException, NoModificationAllowedException {

       boolean append = false;
       if (offset > 0) {
           this.truncateFileAtURL(inputURL, offset);
           append = true;
       }

       byte[] rawData;
       if (isBinary) {
           rawData = Base64.decode(data, Base64.DEFAULT);
       } else {
           rawData = data.getBytes(Charset.defaultCharset());
       }
       ByteArrayInputStream in = new ByteArrayInputStream(rawData);
       try
       {
       	byte buff[] = new byte[rawData.length];
           String absolutePath = filesystemPathForURL(inputURL);
           FileOutputStream out = new FileOutputStream(absolutePath, append);
           try {
           	in.read(buff, 0, buff.length);
           	out.write(buff, 0, rawData.length);
           	out.flush();
           } finally {
           	// Always close the output
           	out.close();
           }
           if (isPublicDirectory(absolutePath)) {
               broadcastNewFile(Uri.fromFile(new File(absolutePath)));
           }
       }
       catch (NullPointerException e)
       {
           // This is a bug in the Android implementation of the Java Stack
           NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
           realException.initCause(e);
           throw realException;
       }

       return rawData.length;
}
 
Example 19
Project: conf4j   File: RootConfigurationProviderTest.java   View Source Code Vote up 4 votes
private void writeConfigToConfigurationFile(File configurationFile) throws IOException {
    FileOutputStream out = new FileOutputStream(configurationFile);
    out.write("someProperty: someValue".getBytes());
    out.close();
}
 
Example 20
Project: SER316-Munich   File: ProjectPackager.java   View Source Code Vote up 4 votes
public static void unpack(File zipfile) {
    try {
        ZipFile zip = new ZipFile(zipfile);
        ZipEntry info = zip.getEntry("__PROJECT_INFO__");
        BufferedReader in = new BufferedReader(new InputStreamReader(zip.getInputStream(info), "UTF-8"));
        String pId = in.readLine();
        String pTitle = in.readLine();
        String pStartD = in.readLine();
        String pEndD = in.readLine();
        in.close();
        if (ProjectManager.getProject(pId) != null) {
            int n =
                JOptionPane.showConfirmDialog(
                    App.getFrame(),
                    Local.getString("This project is already exists and will be replaced.\nContinue?"),
                    Local.getString("Project is already exists"),
                    JOptionPane.YES_NO_OPTION);
            if (n != JOptionPane.YES_OPTION) {
                zip.close();
                return;
            }	
            ProjectManager.removeProject(pId);
        }
        Project prj = ProjectManager.createProject(pId, pTitle, new CalendarDate(pStartD), null);
        if (pEndD != null)
            prj.setEndDate(new CalendarDate(pEndD));
        //File prDir = new File(JN_DOCPATH + prj.getID());
        Enumeration files;           
        for (files = zip.entries(); files.hasMoreElements();){
            ZipEntry ze = (ZipEntry)files.nextElement();
            if ( ze.isDirectory() )
            {
               File theDirectory = new File (JN_DOCPATH + prj.getID()+ "/" + ze.getName() );
               // create this directory (including any necessary parent directories)
               theDirectory.mkdirs();
               theDirectory = null;
            }
            if ((!ze.getName().equals("__PROJECT_INFO__")) && (!ze.isDirectory())) {
                FileOutputStream out = new FileOutputStream(JN_DOCPATH + prj.getID() +"/"+ ze.getName());
                InputStream inp = zip.getInputStream(ze);
                
                byte[] buffer = new byte[1024];
                int len;

                while((len = inp.read(buffer)) >= 0)
                  out.write(buffer, 0, len);

                inp.close();
                out.close();
                
            }
        }
        zip.close();
        CurrentStorage.get().storeProjectManager();             
    }
    catch (Exception ex) {
        new ExceptionDialog(ex, "Failed to read from "+zipfile, "Make sure that this file is a Memoranda project archive.");
    }
}