Change csv file path to internal storage - java

I'm doing a little app that inserts people and then if i want export it to CSV. I was able to do that but the file it's exporting to the sd card of the emulator and i wanted it to export do the internal storage (Downloads or another place). I already searched here to see if i could find an answer but nothing i found resolved my problem.
File dbFile = getDatabasePath("androidituts");
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "teste.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = mydb.rawQuery("SELECT * FROM test", null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
String arrStr[] = {curCSV.getString(1)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
} catch (Exception sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
Does anyone know can i change the file path?? I think that it's in the part Environment.getExternalStorageDirectory, but anytime i change that to anything else it says:
E/MainActivity(1519): open failed: ENOENT (No such file or directory)
E/MainActivity(1519): java.io.IOException: open failed: ENOENT (No such file or directory)

Hope this will help
try {
File exportDir = new File(myDir + "/text/", filename);
if (exportDir .getParentFile().mkdirs()) {
exportDir .createNewFile();
FileOutputStream fos = new FileOutputStream(exportDir );
fos.write(outputString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}

replace
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
to
File exportDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"");

Related

How to save a File to any specific path in Android

I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?
Codes:
public void createFile() {
File path = new File(this.getFilesDir().getPath());
String fileName = "myfile.txt";
String value = "example value";
File output = new File(path + File.separator + fileName);
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
UPDATE :
I fixed the problem. Maybe someones to helps. Only changing this line.
File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");
You can use the following method to get the root directory:
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.
See more here:
https://developer.android.com/training/data-storage/files.html#WriteExternalStorage
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

Text file give error - Transfer error: No such file or directory - DDMS

I'm trying to pull my text file which the name of the file was programmed according to the title of an article which is MACC is on the right track, let’s hope it will go all the way.txt but on pull it gives me this error :
[2016-08-29 11:59:06 - ddms] transfer error: No such file or directory
[2016-08-29 11:59:06] Failed to pull selection: No such file or directory
When I try to delete
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:206)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:707)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
my source code
public void storeHTML(Context context, ArrayList<String> storeHTML) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "voicethenews");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, storeHTML.get(0) + ".txt");
FileWriter writer = new FileWriter(gpxfile);
//BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(int i = 1; i < storeHTML.size(); i++) {
//bufferedWriter.newLine();
writer.append(System.getProperty("line.separator") + storeHTML.get(i));
}
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
I've searched high and low for the answer put still didn't manage to solve it. Thank you.
Please test this code:
Environment.getExternalStorageDirectory().getAbsolutePath()+ "/SOME_DIRECTORY"

Can't write my arrayList to a file as expected

I have this method, supposed to write an arrayList to a file:
private ArrayList<String> readFromFile() {
String ret = "";
ArrayList<String> list = new ArrayList<String>();
try {
InputStream inputStream = openFileInput("jokesBody.bjk");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
list.add(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
System.out.println("DA CRAZY FILE: " + ret);
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return list;
}
The problem with it is that it writes the values like [item1, item2, item3] and later when I need to load a the values back to a listArray it's loading the whole line at index 0. Now I have found the corerct way to write and read the arrayList, but I'm having troubles accessing teh file.
Here is the code I tried:
private void writeToFile(ArrayList<String> list) {
try {
FileOutputStream fos = new FileOutputStream("jokesBody.bjk");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list); // write MenuArray to ObjectOutputStream
oos.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
But it throws the following exception:
02-12 09:21:10.227: E/Exception(2445): File write failed: java.io.FileNotFoundException: /jokesBody.bjk: open failed: EROFS (Read-only file system)
Where is the mistake, where is the default app file location? I know that I'm missing something small, but as an android beginner, I'm not able to spot it.
Isn't this:
java.io.FileNotFoundException: /jokesBody.bjk: open failed: EROFS (Read-only file system)
the issue ? You're writing to a non-writeable area. Change where you're writing to (perhaps creating a temporary file would be a simple first step - I'm not familiar with Android but I assume this is possible)
Your file seems to be read only. You cannot write to a read only file!!!
I don't think you're actually saving the file where you think you are. Look at this tutorial on writing a file to external storage. A few things:
(1) You need to request permission in your manifest to write to external storage. If not you will end up with a read only situation.
(2) You need to get the external storage directory in your code before you write to it. This should be preceeded with a general check as to whether your file directory is writeable in the first place:
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
You can then create a specific directory for the files you want to store and store them in that location so you can find them later. For example:
public File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
You can then write content to the file that is returned
When you are developing for Android, you must get the OutputStream from the Context:
fos = context.openFileOutput("jokesBody.bjk", Context.MODE_PRIVATE);
An explanation about how to work with files on Android is here: Saving Files

Issue creating a file in android

I am trying to create a file inside a directory using the following code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE);
Log.d("Create File", "Directory path"+directory.getAbsolutePath());
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
Log.d("Create File", "File exists?"+new_file.exists());
When I check the file system of emulator from eclipse DDMS, I can see a directory "app_themes" created. But inside that I cannot see the "new_file.png" . Log says that new_file does not exist. Can someone please let me know what the issue is?
Regards,
Anees
Try this,
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
try
{
new_file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Create File", "File exists?"+new_file.exists());
But be sure,
public boolean createNewFile ()
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).
Creating a File instance doesn't necessarily mean that file exists. You have to write something into the file to create it physically.
File directory = ...
File file = new File(directory, "new_file.png");
Log.d("Create File", "File exists? " + file.exists()); // false
byte[] content = ...
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content);
out.flush(); // will create the file physically.
} catch (IOException e) {
Log.w("Create File", "Failed to write into " + file.getName());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
Or, if you want to create an empty file, you could just call
file.createNewFile();
Creating a File object doesn't mean the file will be created. You could call new_file.createNewFile() if you wanted to create an empty file. Or you could write something to it.

Problem in Zipping a File

When I run my code and use the files that are in the resource folder of my project itself, I face no problems. It zips the file successfully and I can extract it using WINZIP. The problem comes when I try to zip a file that is not in the project folder.
When I do the same, I am passing the Absolute Path of both the src and the dest files. My program doesn't give any exceptions, but when I try to open that zip file, I get an error saying, File is Invalid.
Can anyone tell me why this may be happening.
public static void compress(String srcPath, String destPath) {
srcFile = new File(srcPath);
destFile = new File(destPath);
try {
fileInputStream = new FileInputStream(srcFile);
fileOutputStream = new FileOutputStream(destFile);
zipEntry = new ZipEntry(srcPath);
zipOutputStream = new ZipOutputStream(fileOutputStream);
zipOutputStream.putNextEntry(zipEntry);
byte[] data = new byte[12];
while ((fileInputStream.read(data)) != -1) {
zipOutputStream.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
fileInputStream.close();
zipOutputStream.close();}catch (Exception e) {
e.printStackTrace();
}
}
}
You should not store paths with drive letters in your zip file because when you try to extract your zip, it will try to create a directory with the name of the drive and fail.
You will need to change your code so that it removes the drive letter from the path before creating the ZipEntry.

Categories

Resources