Writing file into the data dir of another app (root) - java

I'm trying to write a file (FlappyBird2.xml in this example) into the data directory of another app (/data/data/com.dotgears.flappybird/shared_prefs.xml in this example). But the code does literally nothing. I request superuser rights in another activity in the onCreate event. Here's my code:
Button btncheat = (Button) findViewById(R.id.button1);
btncheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String path = "/data/data/com.dotgears.flappybird/shared_prefs/";
File file = new File(path);
file.mkdirs();
path += "FlappyBird2.xml";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
myOutput.write(new String("test").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/edit: I'm trying it like this now:
Button btncheat = (Button) findViewById(R.id.button1);
btncheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String path = "/data/data/com.dotgears.flappybird/shared_prefs/";
String filename = "FlappyBird2.xml";
String string = "test";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su");
runtime.exec("mv " + Environment.getDataDirectory().toString() + filename + " " + path + filename);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
But this doesn't do anything either. It creates the file in /data/data/my.app/files successfully, but the mv command does not do anything. I see that it requested SU successfully before trying to move the file, so this can't be the problem. Logcat says nothing in red, I debugged it.

Related

Result of File.createNewFile() is ignored

Please I need you to help me to find what I have been doing wrong. I have been having a problem while creating a file using android studio.
There is no error, but the file "textstring.txt" is not created.
W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory) and
W/System.err: at java.io.File.createNewFile(File.java:944) are the warnings I become and it happens at myFile.createNewFile()
This is my code lines
private String INPUT_FILE = "textstring.txt";
private String inputString = "thisIsTheTextToWrite";
private File myFile = null;
private Button myWrite = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create a file
myFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/Data/" + getPackageName() + "/files/" + INPUT_FILE);
mWrite = (Button)findViewById(R.id.b_write);
mWrite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
FileOutputStream output = openFileOutput(INPUT_FILE, MODE_PRIVATE);
output.write(inputString.getBytes());
if(output != null)
output.close();
//
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()))
{
myFile.createNewFile();
output = new FileOutputStream(myFile);
output.write(inputString.getBytes());
if(output != null)
output.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
}
The problem seems to occur at // myFile.createNewFile();
Why that ?
Thank you in advance
It is just a warning right ?
You should always check the result of myFile.createNewFile() :
if(!myFile.createNewFile()) {
Log.e("mDebug", "Couldn't create the file");
}
That's it

I want to convert this code for sounds (trying to share audio files)

I examined similar subjects, but I couldn't do it. I'm trying to share .mp3 file with LongClick button. I found it for JPEG files. One guy created method for sharing jpeg file. How can I convert it for .mp3 files?
package com.example.tunch.trap;
import...
public class sansar extends AppCompatActivity {
private String yardik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sansar);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
yardik = createImageOnSDCard(R.raw.yardik_denizi);
final MediaPlayer yardikdenizi = MediaPlayer.create(this, R.raw.yardik_denizi);
Button btnYardik = (Button) findViewById(R.id.btnSansar_1);
btnYardik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yardikdenizi.isPlaying()){
yardikdenizi.seekTo(0);
}
yardikdenizi.start();
}
});
btnYardik.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(yardik));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
return true;
}
});
}
private String createImageOnSDCard(int resID) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resID);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + resID +".mp3";
File file = new File(path);
try {
OutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e){
e.printStackTrace();
}
return file.getPath();
}
}
This is all Java code. createImageOnSDCard method is for images. I want to use it for my audio file (yardik_denizi.mp3). When I run this, it works but program is trying to send jpeg file. So it doesn't work literally :) How should I change that last part?
You need a method that copies a private raw resource content (R.raw.yardik_denizi) to a publicly readable file such that the latter can be shared with other applications:
public void copyPrivateRawResuorceToPubliclyAccessibleFile(#RawRes int resID,
#NonNull String outputFile) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resID);
outputStream = openFileOutput(outputFile, Context.MODE_WORLD_READABLE
| Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
and then:
copyPrivateRawResuorceToPubliclyAccessibleFile(R.raw.yardik_denizi, "sound.mp3");
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
Uri uri = Uri.fromFile(getFileStreamPath("sound.mp3"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Sound File"));
You should change the path for uri at
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(change_it_path_to_yardik_denizi.mp3));
Finally i got the answer. I can send mp3 files to other apps with this code.
copyFiletoExternalStorage(R.raw.yardik_denizi, "yardik_denizi.mp3");
Uri path= FileProvider.getUriForFile(sansar.this,
"com.example.tunch.trap", new File(Environment.getExternalStorageDirectory() +
"/Android/data/yardik_denizi.mp3"));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
And need to create a method to save data in external store.
private void copyFiletoExternalStorage (int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/"
+ resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Saving and reading txt file when app closed and opened

Now I have app which save and read some text into .txt file by button. How can I make that app save file after app closed and reading file when app opened automatically, without any click on buttons?
public class mAcitivity extends AppCompatActivity {
private Button btn_read, btn_save;
private TextView textView;
private String txt = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
btn_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readFile();
textView.setText(txt);
}
});
}
public String readFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
try {
FileInputStream fis = new FileInputStream(file);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fis.close();
txt = new String(buffer);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mActivity.this, "Error reading file", Toast.LENGTH_LONG).show();
}
return txt;
}
public void saveFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
if (file.exists()){ file.delete();}
try {
String sometxt = "Hello world";
FileOutputStream out = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(out);
pw.println(sometxt);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can use your MainActivity lifecycle callbacks to begin your I/O operations directly, or start BoundService which will operate them.
You can achieve this by putting your saveFile() method inside stop() lifecycle method, and putting your readFile() method inside start() lifecycle method. Activity will automatically call start() method once the application starts and it will call stop() method once the applicqtion closes/terminates.

Android programming : copy folders from assets to /data/data/<packagename> folder

I want to write a project that on first run or installation it copies files and folders from Assets folder( app_webview,cache,databases,files,lib,shared_prefs ) which are folders inside Assets Folder to /data/data/com.example.app/ I saw a code like this around here
i solved this by using this code. you can use this code to send any file from Assets/files/ to any where you want by replacing the getFilesDir().getParent() with the values i will provide below but i havent figure out how to send Folders
package com.paresh.copyfileassetstoAssets;
public class CopyFileAssetsToSDCardActivity1 extends Activity {
/** Called when the activity is first created. */
Button button1;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
CopyAssets();
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Files");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Files/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(getFilesDir().getParent().toString() + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
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);
}
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(CopyFileAssetsToSDCardActivity1.this, CopyFileAssetsToSDCardActivity2.class);
startActivity(intent);
}
});
}
}

Save EditText to file with Button - Android, Java

I have an EditText in which the user inputs their name, then i want to push a button and the content of the EditText is transferred into a file.
EDITED: I have this code so far:
Button submitButton = (Button) findViewById(R.id.baddNametoFile);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try{
ETName.getText().toString();
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
writer.println("<h3 style=padding-left:20px;>" + ETName
+ "</h3><br>");
// new arraylist
writer.close();
}catch (IOException e) {
// put notification here later!!!
e.printStackTrace(); }
}
});
I have it printing to the file what the actual android value is:
android.widget.Button{......./baddNametoFile}
But that is just a placeholder to know the print works. I would like to see what the user has typed printed there instead.
Any help would be great. Thanks
ETName is probably EditText. You didnt post to much code so it should be like:
ETName.getText().toString(); Change View ETName in View v (it is click on a button not on a EditText). Lets try like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String etName = ETName.getText().toString();
if(!etName.trim().equals("")){
File file =new File("/sdcard/Accelerometer.html");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(etName);
bufferWritter.close();
}
}catch (IOException e) {
e.printStackTrace(); }
}
try{
File dir = new File("/mnt/sdcard/MyApp/");
if (!dir.exists()) {
dir.mkdir();
System.out.println("Directory created");
}
//ceate .rtf file with header
myFile = new File("/mnt/sdcard/MyApp/Student.rtf");
if (!myFile.exists()) {
myFile.createNewFile();
System.out.println("File created");
}
fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
myOutWriter = new OutputStreamWriter(fOut);
//Write the header : in your case it is : Student class Marsk (only one time)
myOutWriter.write("Student,class,Marks"+"\n");
myOutWriter.flush();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

Categories