changing byte when copy file form one location to another not working whats wrong in my code please help me if i remove string s1; then its work perfect just duplicate original file when i alter bytes using s1 string its not work
samplet.text file contain numbers
3434214280
3044559080
3154356865
3312430124
3334491537
package com.example.copyfilefromdirectorytoanother;
ublic class MainActivity extends Activity {
private static final String TAG = "MainActivity.java";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your sd card
String sdCard = Environment.getExternalStorageDirectory().toString();
// the file to be moved or copied
File sourceLocation = new File (sdCard + "/sample.txt");
// make sure your target location folder exists!
File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");
// just to take note of the location sources
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else{
// make sure the target file exists
if(sourceLocation.exists()){
InputStream in = new
FileInputStream(sourceLocation);
OutputStream out = new
FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
String s1;
// byte[] theByteArray ;
byte[] buf = new byte[1024];
byte[] theByteArray = new byte[1024];
int len;
int n =1;
while ((len = in.read(buf)) > 0) {
s1= "BEGIN:VCARD \n VERSION:2.1 \n N:;UNKNOWN "+n+";;; \n FN:UNKNOWN "+n+"
\n TEL;CELL;PREF:+92"+buf+" \n END:VCARD ";
theByteArray=s1.getBytes();
out.write(theByteArray, 0, len);
n=n+1;
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file
missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Well, you're reading in len bytes, appending data to it, then writing out len bytes. That's wrong, you need to do out.write(theByteArray, 0, theByteArray.length); I can see other possible problems there too, but your file may be small enough to avoid them.
Related
Trying to use the following code to copy a file from one directory to another and rename
String Path3= "/storage/extSDCard/DCIM/Camera/fred.jpg";
File to = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Barr.jpg");
File oldFile = new File (Path3);
oldFile.renameTo(to);
It doesn't appear to copy the file. in this case the path Path3 is on the SDCard but I also need it to copy from one directory to another on the device as well
Basically I'm using the gallery picker to pick an image from somewhere I convert the uri to a path I then need to copy the file from where it is stored to the pictures directory and rename it
Any idea where I'm going wrong?
I solved it from A variety of sources was going about it in the wrong way. This Code Works:
File sourceLocation = new File (Path2);
File targetLocation = new File (Path3 + "/" + imageFileName);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
int actionChoice = 2;
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
else{
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I am making a soundboard for practice and I want to give the user the ability to download the sound (that I have included in the app in the res/raw folder) onClick of a menu item but I can only find information about downloading from an internet url, not something that I already included in the apk.
What is the best way to do this? I would like to give them the option to save to an SD card also if this is possible. A point towards the correct class to use in the documentation would be great! I've been googling to no avail.
Thanks!
Try something like this:
public void saveResourceToFile() {
InputStream in = null;
FileOutputStream fout = null;
try {
in = getResources().openRawResource(R.raw.test);
String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String filename = "myfile.mp3"
fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
I don't know about the raw but I did a similar thing in my app using the assets folder. My files are under the assets/backgrounds folder as you can probably guess from the code below.
You can modify this code and make it work for you (I know I will only have 4 files which is why I have i go from 0 to 4 but you can change this to whatever you want).
This code copies the file starting with prefix_ (like prefix_1.png, prefix_2.png, etc) to my cache directory but you can obviously change the extension, the filename or the path you would like to save the assets to.
public static void copyAssets(final Context context, final String prefix) {
for (Integer i = 0; i < 4; i++) {
String filename = prefix + "_" + i.toString() + ".png";
File f = new File(context.getCacheDir() + "/" + filename);
if (f.exists()) {
f.delete();
}
if (!f.exists())
try {
InputStream is = context.getAssets().open("backgrounds/" + filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) {
Log.e("Exception occurred while trying to load file from assets.", e.getMessage());
}
}
}
I have searched a lot but it seems older answers are wrong as storage seems to have changed from data/data and permission WRITE_INTERNAL_MEMORY is no longer available. I am using Eclipse.
I have a multi-choice test and want to store the status of the answers a user has given:
N = not attepmpted, C = Correct last time, I = Incorrect last attempt
Therefore the file needs to be re-writeable - will be read as an array and then the array with new status will be over-written.
The code to write the file on first run is - you can see I've just changed it to write "N" now rather than lines of "N" as needed. There is also a single-line txt file to store the user id:
public void RunFirst(View view) throws IOException{
//need to initialise file as a list of N's:
count = 0;
StringBuilder sb = new StringBuilder();
while(count<4){
sb.append("N");
sb.append("\n");
count = count +1;
};
NsString = sb.toString();
String progfile = "userprogress.txt";
try {
FileOutputStream fos = new FileOutputStream(progfile);
fos = openFileOutput(progfile, Context.MODE_PRIVATE);
fos.write(NsString.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
// read userID
TextView usrID = (TextView) findViewById(R.id.editTextUserNameInput);
userID = usrID.getText().toString();
Toast.makeText(getApplicationContext(), "Welcome" + userID,
Toast.LENGTH_LONG).show();
//save userID
String usridfile = "userid.txt";
try{
FileOutputStream fosuserid = new FileOutputStream(usridfile);
fosuserid = openFileOutput(usridfile, Context.MODE_PRIVATE);
fosuserid.write(userID.getBytes());
fosuserid.close();
Toast.makeText(getApplicationContext(), "filesaved",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
To read from the file:
private void readprogressfile(){
//#Override
try
{
Toast.makeText(getApplicationContext(), "b4 file",
Toast.LENGTH_LONG).show();
InputStream input = openFileInput("userprogress.txt");
InputStreamReader isr = new InputStreamReader(input);
BufferedReader buffrdr = new BufferedReader(isr);
userprog = new String [4];
int size = input.available();
byte[] buffer = new byte[size];
count = 0;
line = null;
while(count <4){
input.read(buffer);
line = new String(buffer);
userprog[count]= line;
Toast.makeText(getApplicationContext(), "status:" + count + userprog[count],
Toast.LENGTH_LONG).show();
};
input.close();
// byte buffer into a string
String text= new String(buffer);
//txtContent.setText(text);
Toast.makeText(getApplicationContext(), "after file",
Toast.LENGTH_LONG).show();
TextView showfile = (TextView)findViewById(R.id.textViewShowAns);
showfile.setText("Q status:"+ userprog[qno]);
}catch (IOException e) {
e.printStackTrace ();}
}
;
}
the fact that WRITE_INTERNAL_MEMORY permission is deprecated don't mean that you can't write to internal memory anymore. actually, it's the opposite - Google decided there is no need in any permission to write / create files in your private internal folder.
you can get path to your private application storage folder by the method getFilesDir()
this is the perfect place to write your private files, and made especially for that purpose.
as Google wrote in the documentation:
You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.
source and more info on - http://developer.android.com/training/basics/data-storage/files.html
I have a html file in my asset directory and i have to load it as browser application using Intent.
Here is my code, but its not working:
startActivity (new Intent(Intent.ACTION_VIEW,
Uri.parse("file:///android_asset/Sample.htm")));
Could anyone help me?
Use loadUrl() method of WebView to load an html page
Sample Example
if faq.html is the html file present in assets folder then you can use
WebView html = (WebView) findViewById(R.id.webEulaView);
html.loadUrl("file:///android_asset/faq.html");
i had the same problem what i did was
copied the content of the assets to a database and then pulled it from the sdcard
here is the code to copy your assets to sdcard
the logic used is as follows the html pages are put in the zip file in assets folder
content is the name of the zip in assets folder
boolean succussFlag = false;
destination="";
destination=Environment.getExternalStorageDirectory()+"/";
File file = new File(destination);
if (!file.exists()){
file.mkdirs();
}
else
{
//file.delete();
//file.mkdir();
}
try
{
InputStream fileInput = context.getAssets().open("content.zip");
ZipInputStream inputStream = new ZipInputStream(fileInput);
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry())
{
String innerFileName = destination + entry.getName();
System.out.println("destination::::"+innerFileName);
// Log.v("inner file name 0",""+innerFileName);
File innerFile = new File(innerFileName);
if (innerFile.exists())
{
innerFile.delete();
}
// Check if it is a folder
if (entry.isDirectory())
{
// Its a folder, create that folder
innerFile.mkdirs();
}
else
{
// System.out.println(" ::::::::::::::INNER FILE COPYING :::: " + innerFile.toString());
FileOutputStream outputStream = new FileOutputStream(innerFileName);
final int BUFFER = 4096;
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream,
BUFFER);
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1)
{
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
inputStream.closeEntry();
}
inputStream.close();
// System.out.println(" ::::::::::COPIED TO PRIVATE FOLDER :::: " );
succussFlag=true;
}
catch (IOException e)
{
// System.out.println("** EXCEPTION OCCURED WHILE COPYING***");
e.printStackTrace();
succussFlag=false;
}
return succussFlag;
after this you give following command
startActivity (new Intent(Intent.ACTION_VIEW,"file://"+ Environment.getExternalStorageDirectory()+"/content"+name_Html ;
);
I am trying to create a folder and several subdirectory within it on the SD Card... I then want to transfer files that I have stored in /res/raw to that folder... I addition, I want this to only happen once, the first time the program is ever run. I realize that this is ridiculously open-ended, and that I am asking a lot... but any help would be greatly appreciated.
This will copy all files in the "clipart" subfolder of the .apk assets folder to the "clipart" subfolder of your app's folder on the SD card:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String basepath = extStorageDirectory + "/name of your app folder on the SD card";
//...
// in onCreate
File clipartdir = new File(basepath + "/clipart/");
if (!clipartdir.exists()) {
clipartdir.mkdirs();
copyClipart();
}
private void copyClipart() {
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(int i=0; i<files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + files[i]);
out = new FileOutputStream(basepath + "/clipart/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I experienced a similar problem when using mkdirs(), however because running the command:
mkdir one/two
fails on Linux, then the method http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdirs() subsequently fails too. I guess this means there is no way to use mkdirs on Android? My (probably rather hacky) work-around was to create each necessary directory separately:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
new File(extStorageDirectory + "/one/").mkdirs();
new File(extStorageDirectory + "/one/two/).mkdirs();