AssetManager defination and use:
...
AssetManager mngr = getAssets();
try{
encrypter.decrypt(mngr.open("sample.txt"),output_file);
}...(continued)
decrypt function:
public void decrypt(InputStream in, OutputStream out)
{
try
{
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0)
{
out.write(buf, 0, numRead);
}
out.close();
...(continued)
Its giving error for line out.write(buf, 0, numRead); as java.lang.NullPointerException.
This call was working fine when used as:
*encrypter.decrypt(new FileInputStream("sample.txt"),output_file)* (i.e. when reading file from local than assets directory of android);
Any reasons why?
Any help is appreciated! Thanks!
Your OutputStream is not initialized.So you are getting null pointer exception.you may want
something like this
public void decrypt(InputStream in,String file)
{
try
{
OutputStream out = new FileOutputStream(file);
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0)
{
out.write(buf, 0, numRead);
}
out.close();
Related
I‘m new to Android programming and couldn‘t find a good solution for my problem yet. In my App users can select photos from their gallery which are then used in a Cardview Layout for different categorys in the App which the user can create on his own. By now I‘m able to get Uri of the selected photo and can display it. But how can I save the photo to my App to make sure it‘s always there even though it gets deleted from the gallery?
Ref: How to make a copy of a file in android?
To copy a file and save it to your destination path you can use the method below.
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
On API 19+ you can use Java Automatic Resource Management:
public static void copy(File src, File dst) throws IOException {
t
ry (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
I have a method that takes an image's URL and attempts to save it in memory. I need to retrieve this saved file later, and want to do so by getting its file path. How do I get the file name from this save method?
InputStream input;
try {
URL url = new URL (strURL);
input = url.openStream();
byte[] buffer = new byte[1500];
OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
try {
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
}
finally {
output.close();
buffer = null;
}
}
I am using Android Studio.
Please, suggest me the best way of copying a folder from assets to /data/data/my_app_pkg/files.
The folder from assets (www) contains files and subfolders. which I want to completely copy to the files/ of my internal app path mentioned.
I am successfully able to copy a file from assets to internal app files/ path, but unable to do the same in case of copying folder, even assetmanager.list isn't helping me out, as it is copying only the files, but not the directories / subfolders.
Please kindly suggest me the better way to do what I want
Hope use full to you below code:-
Copy files from a folder of SD card into another folder of SD card
Assets
AssetManager am = con.getAssets("folder/file_name.xml");
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
Hope this will help
private void getAssetAppFolder(String dir) throws Exception{
{
File f = new File(sdcardlocation + "/" + dir);
if (!f.exists() || !f.isDirectory())
f.mkdirs();
}
AssetManager am=getAssets();
String [] aplist=am.list(dir);
for(String strf:aplist){
try{
InputStream is=am.open(dir+"/"+strf);
copyToDisk(dir,strf,is);
}catch(Exception ex){
getAssetAppFolder(dir+"/"+strf);
}
}
}
public void copyToDisk(String dir,String name,InputStream is) throws IOException{
int size;
byte[] buffer = new byte[2048];
FileOutputStream fout = new FileOutputStream(sdcardlocation +"/"+dir+"/" +name);
BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);
while ((size = is.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
is.close();
fout.close();
}
I am trying to share files between two Android phones using Socket programming. The problem is right now I have to hard code the file extension on the receiving end. Is there a way that I can automatically determine the extension of the file being received?
Here's my code.
Client Side
socket = new Socket(IP,4445);
File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = null;
fis = new FileInputStream(myFile);
OutputStream os = null;
os = socket.getOutputStream();
int filesize = (int) myFile.length();
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
socket.close();
}
And the Server side
FileOutputStream fos = null;
File root = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(root,"B.jpg")); //Here I have to hardcode B.jpg with jpg extension.
BufferedOutputStream bos = new BufferedOutputStream(fos);
ServerS = new ServerSocket(4445);
clientSocket = ServerS.accept();
InputStream is = null;
is = clientSocket.getInputStream();
int bytesRead = 0;
int current = 0;
byte [] mybytearray = new byte [329];
do {
bos.write(mybytearray,0,bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
} while(bytesRead > -1);
bos.flush();
bos.close();
clientSocket.close();
}
You can find the file extension pretty easily by doing this:
String extension = filename.substring(filename.lastIndexOf('.'));
I have an API call that returns a byte array. I currently stream the result into a byte array then make sure the checksums match and then write the ByteArrayOutputStream to File. The code is something like this and it works pretty well.
String path = "file.txt";
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
FileOutputStream stream = new FileOutputStream(path);
stream.write(byteBuffer.toByteArray());
My concern i that the result from inputstream could potentially be larger than the heap size in android and I could get OutOfMemory exceptions if the entire byte array is in memory. What is the most elegant way to write the inputStream to file in chunks, such that the byte array is never larger than the heap size?
Don't write to the ByteArrayOutputStream. Write directly to the FileOutputStream.
String path = "file.txt";
FileOutputStream output = new FileOutputStream(path);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
I went with the advice to skip the ByteArrayOutputStream and write to the FileOutputStream and this seems to address my concerns. With one quick adjustment, where the FileOutputStream is decorated by a BufferedOutputStream
String path = "file.txt";
OutputStream stream = new BufferedOutputStream(new FileOutputStream(path));
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = is.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
if(stream!=null)
stream.close();