Here are things I have done:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and
public void createMyFolder(){
File directory = new File(Environment.getExternalStorageDirectory().getPath() + "/myfolder/");
directory.mkdir(); //I had also tried mkdirs()
File file= new File(Environment.getExternalStorageDirectory().getPath() + "/t1.dat");
try {
file.createNewFile();
} catch (IOException e) {}
}
I tested 3 devices and one of them threw exception:
java.io.IOException: Cannot create dir /mnt/sdcard/myfolder
t1.dat was created successfully in /mnt/sdcard/ but myfolder was not.
The device is Xperia Ion with Android version 4.0.4. What's wrong about it and how can I fix it?
Edit: I had tried to create folders by some applications, like File Manager.
And they also failed to create although the sdcard is writable and readable.
I think my phone has some "protections" which do not allow me to create folders in sd card.
But it's funny that my phone allows me to create files instead.
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Replace Environment.getExternalStorageDirectory() with directory and also "/myfolder" will be "/myfolder"
public void createMyFolder(){
File directory = new File(Environment.getExternalStorageDirectory().getPath() + "/myfolder");
directory.mkdir(); //I had also tried mkdirs()
File file= new File(directory.getPath() + "/t1.dat");
try {
file.createNewFile();
} catch (IOException e) {}
}
Related
I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean moveFilesToSentPath(Context context, String type, String filePath, String fileName) {
String folderPath = getFolderPath(type);
File dir;
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File(Environment.DIRECTORY_MOVIES *//*+ "/" + fileName*//*);
}else {*/
dir = new File(this.context.getFilesDir().toString() + "/" + folderPath); // }
if (!dir.exists()) {
dir.mkdirs();
File nomediaFile = new File(dir.getAbsoluteFile(), ".nomedia");
try {
if (!nomediaFile.exists()) {
nomediaFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File from = new File(filePath);
File to = new File(dir + "/" + fileName);
Log.v(TAG, "moveFilesToSentPathFrom= " + from);
Log.v(TAG, "moveFilesToSentPathTo= " + to);
if (from.exists()) {
try {
FileUtils.copyFile(from, to);
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
I want to copy video file from its original location to my own created destination i.e. like (Environment.DIRECTORY_MOVIES + "/" + "video" + "/"+fileName) and then access the file from destination. And also plz elaborate the media store api usage for saving file at specific location
The above code is for api level lower than 30, but need solution for android 11 api level 30 as we can't access storage due to security reasons but instead they provide with media store api, I don't have much idea with media store api. Thanks in advance for the help.
I want to create log file and write some text to that file in java .I completed that task.when run jar file this code working well.but after create setup.exe using exe4j file writing process not working.any one know how to do this?
this is how I get path of jar file located directory
File f = null;
public String baseUrl() {
try {
if (f == null) {
f = new File(Register.class.getProtectionDomain().getCodeSource().getLocation().toURI().getRawPath());
}
String path = f.getParent();
return path;
} catch (URISyntaxException ex) {
System.out.println(ex);
}
return "";
}
This is my log file creating process
try {
src.Log lg = new src.Log();
lg.setAction(action);
lg.setUserName(userName);
lg.setDescription(description);
lg.setTime(date);
lg.setSyncPath(syncPath);
lg.setMethod(method);
String url = baseUrl();
System.out.println(baseUrl());
String directoryName = url + "/ResFile";
File directory = new File(directoryName);
if (!directory.exists()) {
directory.mkdir();
}
File log = new File(directoryName + "/log.txt");
if (log.exists() == false) {
log.createNewFile();
}
try (PrintWriter out = new PrintWriter(new FileWriter(log, true))) {
out.append(lg.toString());
}
} catch (Exception ex) {
System.out.println(ex);
}
If you use the "JAR in EXE" mode, your log file will end up in a temporary directory, because that's where the JAR files are extracted at run time.
To get the directory where the executable is located, you can use
System.getProperty("install4j.exeDir")
I have a Java Class UpdateStats in WEB-INF/Classes directory of a dynamic web application.This class has a function writeLog() which writes some logs to a text file.I want this text file to be in webcontent directory.Thus everytime the function is called updates stats are written in that text file.
The problem is how to give the path of that text file in webcontent directory from within that function,which resides in WEB-INF/Classes directory.
You can get your webapp root directory from ServletContext:
String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();
Hope this helps.
You can do something like below in your servlet,
When you do getServletContext().getRealPath() and put some string argument the file will see at your webcontent location.
If you want something into WEB-INF, you can give fileName like "WEB-INF/my_updates.txt".
File update_log = null;
final String fileName = "my_updates.txt";
#Override
public void init() throws ServletException {
super.init();
String file_path = getServletContext().getRealPath(fileName);
update_log = new File(file_path);
if (!update_log.exists()) {
try {
update_log.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error while creating file : " + fileName);
}
}
}
public synchronized void update_to_file(String userName,String query) {
if (update_log != null && update_log.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(update_log, true);
fos.write((getCurrentFormattedTime()+" "+userName+" "+query+"\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
To write a file you need to know absolute path of your web content directory on server as file class require absolute path.
File f = new File("/usr/local/tomcat/webapps/abc/yourlogfile.txt");
FileOutputStream out = new FileOutputStream(f);
out.writeLog("Data");
Assumption : abc is your project name
WebContent is not any directory when you deploy application. All files under web content goes directly under project name.
i have been trying to get a screenshot lately but every thing in vain the folders are created in android emulator with api level 8. i have mentioned the code below.
In the this code Method takeScreenShot() is supposed to create a directory and store the image while executing as android junit testcase i get result as 100% but not the folders are not Created and screen shot is not stored. should i root my phone to use its sd card ?
public class NewRobotiumTest extends ActivityInstrumentationTestCase2 {
......
......
// actual testcase
public void testRecorded() throws Exception {
solo.waitForActivity("com.botskool.DialogBox.DialogBox",
ACTIVITY_WAIT_MILLIS);
solo.clickOnButton("Show Alert");
solo.clickOnButton("Ok");
solo.clickOnButton("Show Yes/No");
takeScreenShot(solo.getViews().get(0), "testRecorded_1316975601089");
solo.sleep(2000);
solo.clickOnButton("Yes");
solo.clickOnButton("Show List");
solo.clickOnScreen(118f, 563f);
}
/**
* I have added this to the android-manifest.xml file
*
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
*
*/
public void takeScreenShot(final View view, final String name)
throws Exception {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b = view.getDrawingCache();
FileOutputStream fos = null;
try {
final String path = Environment.getExternalStorageDirectory()+ "/test-screenshots/";
File dir = new File("/mnt/sdcard/test-screenshots");
if(!dir.mkdirs()){
System.out.println("Creaet sd card failed");
}
if (!dir.exists()) {
System.out.println(path);
dir.mkdirs();
}
fos = new FileOutputStream(path + name + ".jpg");
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (IOException e) {
}
}
});
}
}
You need add permission to write to the SD Card in the main application. Not the JUnit test project!
Add this to the project manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>