How to save a File to any specific path in Android - java

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)

Related

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"

android creating .txt and .csv files throwing ENOENT No such file or directory exception

I've created an app and i'm just adding in the feature to export data as a .txt or .csv file but I'm getting an error on file creation. The error in logcat appears as File write failed: java.io.IOExcepion: open failed: ENOENT (NO such file or directory).
Can anyone see where i'm making a mistake?I call the writeToFile() method passing either String txt; or String csv; into it depending on which file type is needed.code:
String txt = ".txt";
String csv = ".csv";
private void writeToFile(String fileType) {
// if file name has not been entered...
if (filename.equals("")||filename.equals(null)) {
//display toast
toastMsg = "Please enter a file name";
toast();
}
// else if file name has been entered...
else if (!filename.equals("")) {
// create FileCheck
File fileCheck = new File("/sdcard/" + filename + fileType);
// if file exists...
if (fileCheck.exists()) {
// display toast
toastMsg = "Export Error: File already exists";
toast();
}
// if file does not exist...
else if (!fileCheck.exists()) {
try {
// create file
File myFile = new File("/sdcard/" + filename + fileType);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOSW = new OutputStreamWriter(fOut);
myOSW.append("file data here");
myOSW.close();
fOut.close();
// display toast
toastMsg = "file created: " + myFile.toString();
toast();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
toastMsg = "file write failed: " +e.toString();
toast();
}
}
}
}
This path doesn't exist:
File myFile = new File("/sdcard/" + filename + fileType);
Maybe you mean:
File myFile = new File("/mnt/sdcard/" + filename + fileType);
Which on some devices may not exist as well (sometimes these linked paths are called sdcard0, sdcard1, external_storage, ...)
You'd better use
File myFile = new File(Environment.getExternalStorageDirectory() + "/" + filename + fileType);
And make sure you set the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In your manifest, which also includes the READ_EXTERNAL_STORAGE permission
did you give these permission in manifest file? if not give it
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
i think this will solve your problem.

Change csv file path to internal storage

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(),"");

How to upload file using java ?

Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);

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.

Categories

Resources