Copy file from Android to Windows - java

I wrote a small app, which creats a XML file on my Android device. No I try to copy it from my phone to my Windows PC. In Windows Explorer I can't see this file specific file, on my phone I can see this file with various file explorers. When I reboot my phone, the file appears in Windows Explorer, but I can't copy it to my desktop.
Here is my code which creates my file:
String filename = "myfile.xml";
String dir = Environment.getExternalStorageDirectory().getPath()+"/"+c.getResources().getString(R.string.app_name);
createDir(dir);
File file = new File(dir,filename);
FileWriter out=null;
try {
String xml = createXml();
try {
out = new FileWriter(file);
out.write(xml);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
My guess is, this code doesn't free the file handle so Androids MTP cannot access this file. This would also explain, why the file is shown and could be deleted (but not able to be transfered to my PC) after rebooting my phone.
Any suggestions what goes wrong?

I think you should refresh the media scanner for that file
sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded))
);

Related

How to save an PNG via code in a Runnable JAR file?

I'm having trouble fixing this issue,
I have created a Client\Server side application and created a Method where a user can
"Send" a PNG file from his side to Server side, then the Server side "Creates" and saves the image in a Package that only contains pictures.
When i run this Method of sending a Picture from Client side to Server side via Eclipse IDE
it works as expected, but when exporting Client/Server side into Runnable JAR files, i get the next error:
Java
private static void getImg(MyFile msg) {
int fileSize =msg.getSize();
System.out.println("length "+ fileSize);
try {
File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
FileOutputStream fileOut;
fileOut = new FileOutputStream(newFile);
BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut);
try {
bufferOut.write(msg.getMybytearray(), 0, msg.getSize());
fileOut.flush();
bufferOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I get the follow error :
java.io.FileNotFoundException: java.io.FileNotFoundException: C:\Users\Ilya\Desktop\src\GuiServerScreens\test.png (The system cannot
find the path specified)
It seems that using File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
Does not provide the wanted result
I think you are mixing what your directories look like in netbeans with what's available on the server. Save to an external directory instead, not to your src directory.

I want to write In a CSV file Under Movies directory of the internal storage

I want to write In a CSV file Under Movies directory of the internal storage. How can i create a .CSV file and how can i write something into it. it should work in latest android like Android 11. I'm using below code But this code actually throwing Open Failed EPERM (operation not permitted) Exception:
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/NewFolder","newFile.csv");
FileOutputStream f;
try {
f = new FileOutputStream(file, true);
try {
String title = "X Coord, Y Coord, Z Coord, Accelerometer\n";
f.write(title.getBytes());
f.flush();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
How can i resolve this issue?
I want to write In a CSV file Under Movies directory
On an Android 11+ device your app is only allowed/permitted to create movie files in the Movies directory.
A file with a .csv extension will not go.
If you give the file an mp3 extension it will succeede.
Try the public Documents directory instead for a *.csv file.

Why Isn't My FileOutputstream Writing to a File?

I'm a beginner working on an Android app that uses the gcacace SignaturePad library to capture the signature of my user. My goal is to take the signature, compress it down into a JPEG, and then write that information to a file on the users phone so the picture can be accessed later.
I am currently getting no errors or crashes when I run the code, yet no directory or file is being created when I test the app out on my device(Google Pixel 2). Can anyone give me a hand figuring out where the problem is? I've thrown my head against a wall this entire morning and still don't know.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("images", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File myPath = new File(directory, "1.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
}
signaturePad.getSignatureBitmap().compress(Bitmap.CompressFormat.JPEG, 90, fOut);
Bitmap signature = signaturePad.getSignatureBitmap();
int bytes = signature.getByteCount();
try {
fOut.write(bytes);
fOut.flush();
fOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Toast.makeText(activity_signature_pad.this, "Signature Saved", Toast.LENGTH_SHORT).show();
The code in your question writes to what the Android SDK refers to internal storage. That is private to your app; ordinary users do not have access to it (including you, except when using developer tools).
You appear to want to write to external storage. For that, use:
File directory = new File(getExternalFilesDir(null), "images")

Android Studio write to .properties file

I followed Where to put own properties file in an android project created with Android Studio? and I got an InputStream which reads from my .properties file successfully. However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\userInfo.properties" which also doesn't work.
My .properties file is in src\main\assets\userInfo.properties
Properties props = new Properties();
InputStream inputStream = null;
try{
inputStream = getBaseContext().getAssets().open("userInfo.properties");
props.load(inputStream);
props.put("name", "smith");
FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
props.store(output, "This is overwrite file");
String name = props.getProperty("name");
Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Current code throws this error:
java.io.FileNotFoundException: userInfo.properties (Read-only file system)
You can't write to the assets folder, as it is inside the APK which is read-only.
Use internal or external storage instead
You can't write to the assets folder. If you want to update your properties file, you'll have to put them some place else. If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there.

Android: how to write a file to internal storage

I am developing a simple android application and I need to write a text file in internal storage device. I know there are a lot of questions (and answers) about this matter but I really cannot understand what I am doing in the wrong way.
This is the piece of code I use in my activity in order to write the file:
public void writeAFile(){
String fileName = "myFile.txt";
String textToWrite = "This is some text!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
outputStream.write(textToWrite.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I really cannot understand which mistake I am doing. In addition, I have tried this project on my emulator in Android Studio and my phone in order to understand where I am doing something wrong but even with that project no file is written neither on the phone or on the emulator.
EDIT:
I know that no file is written to my internal storage because I try to read the content of the file, after I have written to it, with this code:
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("myFile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
Nothing is shown at all.
Use the below code to write a file to internal storage:
public void writeFileOnInternalStorage(Context mcoContext, String sFileName, String sBody){
File dir = new File(mcoContext.getFilesDir(), "mydir");
if(!dir.exists()){
dir.mkdir();
}
try {
File gpxfile = new File(dir, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
Starting in API 19, you must ask for permission to write to storage.
You can add read and write permissions by adding the following code to AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can prompt the user for read/write permissions using:
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
and then you can handle the result of the permission request in onRequestPermissionsResult() inside activity called from it.
no file is written neither on the phone or on the emulator.
Yes, there is. It is written to what the Android SDK refers to as internal storage. This is not what you as a user consider to be "internal storage", and you as a user cannot see what is in internal storage on a device (unless it is rooted).
If you want to write a file to where users can see it, use external storage.
This sort of basic Android development topic is covered in any decent book on Android app development.
Save to Internal storage
data="my Info to save";
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Read from Internal storage
try {
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
Android 11 Update
Through Android 11 new policies on storage, You cannot create anything in the root folder of primary external storage using Environment.getExternalStorageDirectory() Which is storage/emulated/0 or internal storage in file manager. The reason is that this possibility led to external storage being just a big basket of random content. You can create your files in your own applications reserved folder storage/emulated/0/Android/data/[PACKAGE_NAME]/files folder using getFilesDir() but is not accessible by other applications such as file manager for the user! Note that this is accessible for your application!
Final solution (Not recommended)
By the way, there is a solution, Which is to turn your application to a file manager (Not recommended). To do this you should add this permission to your application and the request that permission to be permitted by the user:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
Thoriya Prahalad has described how to this job in this stackoverflow post.
To view files on a device, you can log the file location >provided by methods such as File.getAbsolutePath(), and >then browse the device files with Android Studio's Device >File Explorer.
I had a similar problem, the file was written but I never saw it. I used the Device file explorer and it was there waiting for me.
String filename = "filename.jpg";
File dir = context.getFilesDir();
File file = new File(dir, filename);
try {
Log.d(TAG, "The file path = "+file.getAbsolutePath());
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return true;
Have you requested permission to write to external storage?
https://developer.android.com/training/basics/data-storage/files.html#GetWritePermission
Perhaps your try\catch block is swallowing an exception that could be telling you what the problem is.
Also, you do not appear to be setting the path to save to.
e.g: Android how to use Environment.getExternalStorageDirectory()
To write a file to the internal storage you can use this code :
val filename = "myfile"
val fileContents = "Hello world!"
context.openFileOutput(filename, Context.MODE_PRIVATE).use {
it.write(fileContents.toByteArray())
}
This Answer worked for me for android 11+ !! check it out, hopefully it'll work for you too
https://stackoverflow.com/a/66366102/16657358[1]
[(btw, int SDK_INT = 30; it confused me lol so thought i should mention)]

Categories

Resources