Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Tuesday, 4 September 2012

Android; Read file from Assets into Byte Array

Sometimes you want to place an encrypted file in the assets folder, and you want to read it in correct and unencrypted, so, you want to read it into byte array and edit the byte array to the correct format, here is the way


InputStream is=getAssets().open("fileName.extension");
byte[] fileBytes=new byte[is.available()];
is.read( fileBytes);
is.close();

Now you edit the byte array as you want, and you can create original file with the current bytes if it was encrypted



Mohammad Abu Hmead

Tuesday, 28 February 2012

Write into or create Text File on android internal or External Storage


try {
if (writeFile("sdcard/strs.txt", "My string runs here"))
Log.i("WriteFil", "Success");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Here the method:



/**
* This method to create text file or append to a text file
*
* @param fullFileLocationBathWithNameAndExten
* like "sdcard/strs.txt"
* @param text
* : the text which will be written in the file
* @return: sucess if the process finished successfully
* @throws IOException
* : error in creating the file
*/
public boolean writeFile(String fullFileLocationBathWithNameAndExten,
String text) throws IOException {
File file = new File(fullFileLocationBathWithNameAndExten);
if (!file.exists()) {

file.createNewFile();

}

// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(text);
buf.newLine();
buf.close();

return true;

}