I am trying to make an app in which I can take text input from the user store it in a text file and then upload that file to firebase so that I can retrieve it later.
The issue is that I am unable to get the correct URI of the file. Please help me get the URI.
Here is the code
public class TextUpload extends AppCompatActivity {
private void writeToFile(String data, Context context) throws FileNotFoundException {
mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!mediaFile.exists()) {
mediaFile.mkdir();
}
byte[] data2 = data.getBytes();
FileOutputStream f = new FileOutputStream(new File(mediaFile, "textfile.txt"));
try {
f.write(data2);
f.flush();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
fileUri = Uri.fromFile(mediaFile);
Log.d("TAHH" , "URI = "+fileUri);
}
}
This is the value I'm getting stored at fileUri
URI = file:///storage/emulated/0
[
Please help me get the URI of the highlighted file.
Main problem is that you are reading the path of mediaFile which is a directory (not the file itself). mediaFile is the parent directory of the file that you want.
So, change to this:
mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!mediaFile.exists()) {
mediaFile.mkdir();
}
byte[] data2 = data.getBytes();
// Hold the reference to the file that you are writting
File txtFile = new File(mediaFile, "textfile.txt")
FileOutputStream f = new FileOutputStream(txtFile );
try {
f.write(data2);
f.flush();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
// Here, use txtFile instead of mediaFile
fileUri = Uri.fromFile(txtFile);
Log.d("TAHH" , "URI = "+fileUri);
Related
Well, I'm trying to create a folder in my internal storage.
I have watched some tutorial but it's not working at all.
private void createDir() {
String folderName;
folderName = "myFolder";
File file = new File(Environment.getExternalStorageDirectory(), folderName);
if(!file.exists()){
file.mkdir();
Toast.makeText(getContext(),"Successful", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"Folder already exist", Toast.LENGTH_SHORT).show();
}
}
This is my method to create the new directory.
When I launch it, I receive the Toast "Successful" all the time.
But the directory is never created.
Just below the code for the permissions.
if(!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.SEND_SMS)){
String[] permissions = {Manifest.permission.WRITE_CALL_LOG,Manifest.permission.SEND_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_SMS};
ActivityCompat.requestPermissions(getActivity(),permissions,1);
}else{
lay_dataset1=view.findViewById(R.id.lay_dataset1);
messagePerm();
}
Here my manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Can someone explain what is happening :)
EDIT :
private void copyAssets() {
AssetManager assetManager = getContext().getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getContext().getExternalFilesDir(null).getParent().replace("files","myfolder"), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
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 tried this, I was able to move files that were in my "asset" folder at the same level as the "files" directory so why shouldn't I have the right to create a folder in this same location ?
At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.
So try this code..
//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);
/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());
//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();
/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());
I created an android file chooser that returns the uri of a text file. I want to open and read the file and store it's data.My code is:
private void covertFile(Uri data) {
InputStream inputStream = getContentResolver().openInputStream(data);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String myText = "";
int in;
try {
in = inputStream.read();
while (in != -1)
{
byteArrayOutputStream.write(in);
in = inputStream.read();
}
inputStream.close();
myText = byteArrayOutputStream.toString();
}catch (IOException e) {
e.printStackTrace();
}
myTextView.setText(myText);
}
But the line InputStream inputStream = getContentResolver().openInputStream(data); givesjava.Io.FileNotFoundException. How do I resolve this?
EDIT: Issue Resolved
First create file object
String path = data.toString();
File file = new File(path);
Now pass the file object as arg in InputStream
InputStream inputStream = getContentResolver().openInputStream(file);
I have a Byte[] array that i want to put it's content into a temporary file .
I have tryied to do it like this
try {
tempFile = File.createTempFile("tmp", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(sCourrier.getBody());
} catch (IOException e) {
e.printStackTrace();
}
but i want that I specify the filename by myself so not generated by the jvm
You can directly give the location and file name or You can access local filesystem and find the temp directory
String tempDir=System.getProperty("java.io.tmpdir");
you can use temp directory and your custom file name.
public static void main(String[] args) {
try {
String tempDir=System.getProperty("java.io.tmpdir");
String sCourrier ="sahu";
File file = new File(tempDir+"newfile.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sCourrier.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
You can use Guava Files.createTempDir():
File file = new File(Files.createTempDir(), fileName.txt);
But because the API is deprecated and they also recommend to use Nio with more params:
Path createTempDirectory(String prefix, FileAttribute<?>... attrs)
so it would be better if you have a method yourself:
File createTempFile(String fileName, String content) throws IOException {
String dir = System.getProperty("java.io.tmpdir");
File file = new File(dir + fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(content.getBytes(StandardCharsets.UTF_8));
}
return file;
}
I am trying to read a pdf file from my assets folder but I do not know how to get the path of pdf file.
I right click on pdf file and select "copy Path" and paste it
Here is the another screen shot of my code:
Here is my code:
File file = new File("/Users/zulqarnainmustafa/Desktop/ReadPdfFile/app/src/main/assets/Introduction.pdf");
if (file.exists()){
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application available to view PDF", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this, "File path not found", Toast.LENGTH_LONG).show();
}
I always get file not found, Help me to create File object or let me know how I can get the exact path for a file I also tried with file:///android_asset/Introduction.pdf but no success. I also tried with Image.png but never gets file.exists() success. I am using Mac version of Android studio. Thanks
get input stream from asset and convert it to a file object.
File f = new File(getCacheDir()+"/Introduction.pdf");
if (!f.exists())
try {
InputStream is = getAssets().open("Introduction.pdf");
byte[] buffer = new byte[1024];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
Short converter (storing asset as cache file) in Kotlin:
fun fileFromAsset(name: String) : File =
File("$cacheDir/$name").apply { writeBytes(assets.open(name).readBytes()) }
cacheDir is just shorthand for this.getCacheDir() and should be predefined for you.
Can you try this code
AssetManager am = getAssets();
InputStream inputStream = am.open("Indroduction.pdf");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("new FilePath");
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;
}
Then try with
File file = new File("new file path");
if (file.exists())
I am working on a Spying application for my college project purpose. For that i have logged the Calls, Location and SMS of the device and stored them in a database. Now i want to export the contents of the database to a text file.. I tried the below code.
private void readAndWriteCallsData() {
File dataBaseFile = getDatabasePath("DATABASE");
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
try {
BufferedReader dbFileReader = new BufferedReader(new FileReader(callDataFile));
String eachLine;
while((eachLine = dbFileReader.readLine()) != null)
{
Callslog.append(eachLine);
Callslog.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
But that is not working... Please help me...
You can encode the database file from binary stream to character stream by Base64, then decode the text when nessesary.
First find a Base64 library. You can use http://sourceforge.net/projects/iharder/files/base64/. There's only one file, "Base64.java".
Code example:
private void readAndWriteCallsData() {
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
try {
FileInputStream fis = new FileInputStream(callDataFile);
try{
byte[] buf = new byte[512];
int len;
while((len = fis.read(buf)) > 0){
String text = Base64.encodeBytes(buf, 0, len); // encode binary to text
Callslog.append(text);
Callslog.append("\n");
}
}finally{
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
To revert it, code like following:
private void revertCallsData() {
File encodedCallDataFile; // get reference to the encoded text file
try {
BufferedReader br = new BufferedReader(new FileReader(encodedCallDataFile));
try{
String line;
while((line = br.readLine()) != null){
byte[] bin = Base64.decode(line); // decode each line to binary, you can get the original database file
}
}finally{
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ok guys after a lot of hit and trial i finally found the solution, here is the code, i saved the functionality in a button.
final String SAMPLE_DB_NAME = "MyDBName.db";//database name
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "your package name" +"/databases/"+SAMPLE_DB_NAME;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(getApplicationContext(),"Your database has been exported",
Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
});
the database will be saved in /storage/emulated/0/
I would recommend to export into a structered file format such as JSON or CSV. Here is my JSON exporter method. Maybe it helps
private static final String LOG_FOLDER = "/ExportFolder";
private static final String FILE_NAME = "export_file.json";
public static void exportMeasurementsJSON(Handler mHandler) {
sendToastMessage("Export to JSON started", mHandler);
File folder = new File(Environment.getExternalStorageDirectory()
+ LOG_FOLDER);
if (!folder.exists())
folder.mkdir();
final String filename = folder.toString() + "/"
+ getLogFileName(".json");
try {
FileWriter fw = new FileWriter(filename, false /* append */);
// get the db
SomeDateSource db = PIApplication.getDB();
// Google Gson for serializing Java Objects into JSON
Gson mGson = new GsonBuilder().create();
Cursor c = db.getAllRows();
if (c != null) {
while (c.moveToNext()) {
fw.append(mGson.toJson(new DBEntry(c
.getString(1), c.getString(2), c
.getDouble(3), c.getLong(4))));
fw.append('\n');
}
c.close();
}
fw.close();
sendToastMessage("Export finished", mHandler);
} catch (Exception e) {
sendToastMessage("Something went wrong", mHandler);
e.printStackTrace();
}
}
If you're interested I can also add my CSV exporter.
Your question is not that clear (Are you trying to copy the file to an alternative location or export the actual data from it?)
If you only wish to copy the file, you can copy the db file using the following method:
public static void copyFile(String sourceFileFullPath, String destFileFullPath) throws IOException
{
String copyFileCommand = "dd if=" + sourceFileFullPath + " of=" + destFileFullPath;
Runtime.getRuntime().exec(copyFileCommand);
}
Simply call that method with your database file path (/data/data/package_name/databases/database_name) as sourceFileFullPath and your target file path as destFileFullPath. You can than use tools such as SQLite Expert to view the content of the database on your PC/Laptop.
If your intention is to export the data from the database and store it in a text file (a CSV file or anything similar), then you should not read the database file content, and instead use the SQLiteDatabase class to query each table contents into a Cursor and iterate it to write each cursor row into a text file.
You could export the entire db into your sdcard folder and then use SQLite manager to open and see it's content.
A Example is available here: http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
Here is the complete method for writing the Database in the SD Card:
/**
* Copy the app db file into the sd card
*/
private void backupDatabase(Context context) throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/yourappPackageName/databases/yourDBName.db";
// OR use- context.getFilesDir().getPath()+"/databases/yourDBName.db";//
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/"+SQLiteDataHelper.DB_NAME;
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
}
Hope it will help you.
One way to do this (I assume its a long procedure, easy one though), if you know the database and get all the tables and retrieve info from those tables. Since, we are talking about sqlite DBs, I assume it will be small.
SELECT * FROM dbname.sqlite_master WHERE type='table';