manually read a file in the files directory - android

Friends, My application has to get current gps position in every seconds and write this data as byte array to a file in files directory. To check the data in that file I tried to open mnually. But i couldn't open. How can i read the file. The file is a text file

private static String readFileAsString(String file) throws IOException {
byte[] bytes = new byte[(int) new File(file).length()];
BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));
stream.read(bytes);
return new String(bytes);
}

Related

How to upload big videos files to server quickly in android

Hi I am uploading Large video files to server using Volley Multi-part Api but it takes much time for upload to server
Is it better to split my video files and send to server? If it is better please provide me code how can I do that, If not what is the best way to uploading big videos files to server quickly?
To split file into parts (chunks):
public static List<File> splitFile(File f) throws IOException {
int partCounter = 1;
List<File> result = new ArrayList<>();
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles]; // create a buffer of bytes sized as the one chunk size
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
String name = f.getName();
int tmp = 0;
while ((tmp = bis.read(buffer)) > 0) {
File newFile = new File(f.getParent(), name + "." + String.format("%03d", partCounter++)); // naming files as <inputFileName>.001, <inputFileName>.002, ...
FileOutputStream out = new FileOutputStream(newFile);
out.write(buffer, 0, tmp);//tmp is chunk size. Need it for the last chunk, which could be less then 1 mb.
result.add(newFile);
}
return result;
}
This method will split your file to chunks of size of 1MB (excluding the last chunk). After words you can send all these chunks too the server.
Also if you need to merge these files:
public static void mergeFiles(List<File> files, File into)
throws IOException {
BufferedOutputStream mergingStream = new BufferedOutputStream(new FileOutputStream(into))
for (File f : files) {
InputStream is = new FileInputStream(f);
Files.copy(is, mergingStream);
is.close();
}
mergingStream.close();
}
Just in case if your server is in Java also

Copy one database to another directory

I'd like to copy one file to another directory. These files are database files. I've got something like this but I got error like:
05-15 13:15:01.055: W/System.err(31247): java.io.FileNotFoundException: /mnt/sdcard/storeUGif/backup/gifs.db (No such file or directory)
My destination paths:
public static final String DATABASE_INPUT_BACKUP = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/storeUGif/" + SqliteHelper.DATABASE_NAME;
public static final String OUTPUT_BACKUP_DATABASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/storeUGif/backup/" + SqliteHelper.DATABASE_NAME;
This is my code:
private void copyDatabase() throws IOException {
File outPut = new File(Tools.OUTPUT_BACKUP_DATABASE);
File inPut = new File(Tools.DATABASE_INPUT_BACKUP);
FileInputStream is = new FileInputStream(inPut);
OutputStream os = new FileOutputStream(outPut);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}
I'd like to make copy of file from source folder to OUTPUT_BACKUP but I got this error. How to solve it?
I think its because the backup folder does not exist. Add this line of code here:
File outPut = new File(Tools.OUTPUT_BACKUP_DATABASE);
outPut.mkdirs();
This should create all folders needed, and if the folders already exist it won't hurt anything.

How to load a file from assets folder of my android test project?

Is there a way to get the file object of one of the files which are inside the assets folder. I know how to load the inputstream of such a file, but i need to have a file object instead of the inputstream.
This way i load the inputstream
InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
But I need the file object, this way the file will not be found
File f = new File("assets/example.stf2");
Found a soltion which works in my case, mabye someone else can use this as well.
Retrieving the file from my android test project to an inputstream
InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
Create a file on the External-Cachedir of the android application under test
File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");
Copy the inputstream to the new file
FileUtils.copyInputStreamToFile(input, f);
Now I can use this file for my further tests
try below code:-
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
for more info see below link :-
How to pass a file path which is in assets folder to File(String path)?

Gmail file attachment download is failing with getContentResolver()

I'm writing a process that downloads/ copies a file attached to Gmail on to the SD card that my application can then read.
When a user clicks on the attachment my activity is fired and I use the following code to save to local storage;
InputStream in = getContentResolver().openInputStream( intent.getData() );
String ext = intent.getType().equals("text/xml") ? ".xml" : ".gpkg";
localFile = new File( TILE_DIRECTORY, "tmp/"+intent.getDataString().hashCode()+ext);
// If we haven't already cached the file, go get it..
if (!localFile.exists()) {
localFile.getParentFile().mkdirs();
FileIO.streamCopy(in, new BufferedOutputStream(new FileOutputStream(localFile)) );
}
The FileIO.streamCopy is simply;
public static void streamCopy(InputStream in, OutputStream out) throws IOException{
byte[] b = new byte[BUFFER];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
out.close();
in.close();
}
This all works fine on a small file, but with a 6Mb attachment only 12Kb is ever getting written. I'm not even getting an error, the process just runs through very quickly and i'm left with a corrupt file.
This process is run in its own thread and is part of a larger app with a lot of fileIO, so there is no issue with permissions/ directories etc.
Is there something different I should be doing with the stream?
Incidentally, intent.getData() is
content://gmail-ls/mexxx#gmail.com/messages/6847/attachments/0.1/BEST/false
and intent.getType() is
application/octet-stream
Thanks
All work's fine with this code
InputStream in = new BufferedInputStream(
getContentResolver().openInputStream(intent.getData()) );
File dir = getExternalCacheDir();
File file = new File(dir, Utils.md5(uri.getPath()));
OutputStream out = new BufferedOutputStream( new FileOutputStream(file) );
streamCopy(in, out);

Can't read file from android internal storage into byte array

I am trying to save a p12 file to internal storage like so:
File file = new File(mContext.getFilesDir(), "fileName.p12");
I then proceed to read this file into a byte array like so:
byte[] bFile = new byte[(int) file.length()];
try {
bFile = org.apache.commons.io.FileUtils.readFileToByteArray(file);
}catch(Exception e){
e.printStackTrace();
}
After doing this, I get a FileNotFoundException even though the debugger shows that the file is saved in /data/data/com.fm.sg.android/files/fileName.p12
What am I doing wrong?
path = context.getFilesDir().getAbsolutePath().toString();
String filename = "fileName.p12";
File file = new File(path,filename);
then the rest of your code....this should make it...

Categories

Resources