I'm trying to create a folder for save files if it doesn't already exist, but I can't find the folders I'm creating in the filesystem after I run my code.
Here's the event handler for my login button:
#FXML
private void loginBtnAction(ActionEvent event) {
// Check for save file folder and create if not exist
splashMessages.appendText("Checking for save folder... ");
File saveFolder = new File("../../saved_profiles/");
if (!saveFolder.exists()) {
splashMessages.appendText(" not found.\n");
try {
saveFolder.mkdir();
splashMessages.appendText("Folder created in " + System.getProperty("user.dir") + "\n");
}
catch (SecurityException se) {
se.printStackTrace();
}
}
else {
splashMessages.appendText(" found.\n");
}
}
If I change ../../saved_profiles/ to something else and click my button, the messages it displays in my textarea suggest that it's created the directory. If I then press the button again, it doesn't try to create another new one, either (i.e. it prints "Checking for save folder... found." to the textarea).
The issue here is that I can't find the folders in my filesystem where it says it's created them. Anybody know where I should look?
To be 100% sure, add a debug line showing the full path:
File saveFolder = new File("../../saved_profiles/");
if (!saveFolder.exists()) {
System.out.println(saveFolder.getAbsolutePath());
...
This will show you the path without any relative segments, so from the root of your filesystem.
Related
How can I rename a directory in java .
I have a directory structure like /workspace/project-name/project/user/wbench/test/<multiple folders & git objects>
In the above structure I want to change test to dev (for example).
I thought Files.renameTo() will do the trick for me but this code is not working.
public ResponseMessage updateDirectoryName(String oldDirectoryName, String newDirectoryName, String userName) {
File projectDirectoryForUser = gitUtils.getProjectDirectoryFromRepoName(userName, oldDirectoryName);
try {
if (projectDirectoryForUser.exists()) {
File newDir = new File(projectDirectoryForUser.getParent()+File.separator+newDirectoryName);
Boolean flag =projectDirectoryForUser.renameTo(newDir);
if(flag){
System.out.println("File renamed successfully");
}else{
System.out.println("Rename operation failed");
}
}
else {
log.info("No folder found for Project in file path");
}
}
catch (Exception e){
log.info("something is not right" + e.getMessage());
}
My flag is always false and name of directory is not changed.
I am certainly doing something wrong not sure what?
I think getParent() must be getParentFile() so you have the full path.
The newer generalisation of File, the class Path, together with the utilities class Files one should better use. Files.move is the equivalent of a File.renameTo and might not in every case work for non-empty directories.
public ResponseMessage updateDirectoryName(String oldDirectoryName,
String newDirectoryName, String userName) {
Path projectDirectoryForUser = gitUtils.getProjectDirectoryFromRepoName(userName,
oldDirectoryName).toPath();
try {
if (Files.exists(projectDirectoryForUser)) {
Path newDir = projectDirectoryForUser.resolveSibling(newDirectoryName);
Files.move(projectDirectoryForUser, newDir);
boolean flag = Files.exist(newDir);
if (flag) {
System.out.println("File renamed successfully");
} else {
System.out.println("Rename operation failed");
}
} else {
log.info("No folder found for Project in file path");
}
} catch (Exception e){
log.info("something is not right" + e.getMessage());
}
}
Whereas File is a disk file, Path can also be from an URI, or a packed "file" in a zip file. Different file system views. This allows File to copy file or java resource into a zip, or rename a file in a zip.
So for the same reason one uses List instead of an implementing ArrayList, one better use Path. Also I read that the Files operations are a bit better than those of File.
You can't change a value os a final variable. Remove the "final" keyword from "projectDirectoryForUser" and try again.
See here
I tried to move a photo taken by the camera to a folder named "raspberrypi" I created. But the .renameTo() keeps returning false. I cannot find the reason. To clarify, the photos I am trying to move are taken by the camera, so they aren't in any folder to begin with.
imagesEncodedList is an ArrayList of File path Strings.
boolean bool=false;
for(int i=0; i<imagesEncodedList.size();i++){
File from;
File to=null;
try{
from=new File(imagesEncodedList.get(i));
String dateString=new SimpleDateFormat("MM_dd_yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
to=new File(getPublicDir(),"SideBySide4_ImportedPhoto"+i+"_"+dateString+".jpg");
bool=from.renameTo(to);
}catch(Exception e){
e.printStackTrace();
}
MediaScannerConnection.scanFile(this,
new String[]{to.getPath()},
null,
null);
}
Toast.makeText(this, "Success?: "+bool, Toast.LENGTH_LONG)
.show();
Here is my getPublicDir() function implementation:
public File getPublicDir() {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "raspberry");
if (!file.mkdirs()) {
Log.e("PUBLIC DIRECTORY", "Directory not created");
}
return file;
}
renameTo only works if source and target are on the same disk partition. If they're not, you'll have to copy the source file and delete it afterwards.
context.getFilesDir() is on a different partition (/data) than Environment.getExternalStoragePublicDirectory (typically accessible under /sdcard).
I'm new to Android Studio 3.0, emulating on a Nexus 4, Marshmallow. I'm trying to build simple "Save File" and "Load File" parts of my app. Here's the "Save File" part:
String filename = "myFile01"; // Then "myFile02", "myFile03", etc...
String userData = "Some useful data here...";
try {
// Adapted from: https://www.youtube.com/watch?v=_15mKw--RG0
FileOutputStream fileOutputStream = openFileOutput(filename, MODE_PRIVATE); // creates a file with given filename
fileOutputStream.write(userData.getBytes()); // puts userData into the file
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "File saved!", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The above code will be called again and again as the user creates and saves additional files. Later, the user may want to view all the saved files and load one. I'll have a ListView displaying all the files... but I need help reading the current directory to get that list.
I thought I read somewhere that in Android, there's one flat directory for your app to save and retrieve files. So I was hoping if I saved a bunch of files and then called a read() method, all my saved files would simply be in the default directory, no need to search. That seems to be a bad assumption; here's why:
Here's my code looking in the default directory and listing all the files found within there. First, I need the path of said default directory:
// Get current directory adapted from: https://stackoverflow.com/questions/5527764/get-application-directory
String packName, currDir;
PackageManager m = getPackageManager();
packName = getPackageName();
PackageInfo p = null;
try {
p = m.getPackageInfo(packName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
currDir = p.applicationInfo.dataDir;
And then I open "currDir," and store the names of all the local files in an array:
// get list of files adapted from: https://stackoverflow.com/questions/9317483/showing-a-list-of-files-in-a-listview#9317583
File dir = new File(currDir);
File[] filelist = dir.listFiles();
String[] fileArr = new String[filelist.length];
for (int i = 0; i < fileArr.length; i++) {
fileArr[i] = filelist[i].getName();
}
The plan from here is to load the "fileArr" into a ListView and go from there. But when I step through the debugger, I see this as the contents of "fileArr":
"cache"
"code_cache"
"files"
This is true no matter how many files I've saved previously.
BTW, in the debugger, the assignments for packName and currDir look 100% correct:
packName = com.mydomain.myapp
currDir = /data/user/0/com.mydomain.myapp
So... I'm kinda assuming that my saved files are actually here:
/data/user/0/com.mydomain.myapp/files
And therefore, I should append this to my "get current directory" code:
// Get current directory adapted from: https://stackoverflow.com/questions/5527764/get-application-directory
String packName, currDir;
...everything from before...
currDir = p.applicationInfo.dataDir+"/files"; // <---- appending "+"/files"
Or am I way off? Any advice will be appreciated, thanks!
First of all, if you want to save your files in the app's directory, then you should call create a directory,
File directoryDefault = new File(Environment.DIRECTORY_DOCUMENTS, "YOUR_FOLDER_NAME");
if (!directoryDefault.exists()) {
directoryDefault.mkdir();
}
Then you have to save whatever files you have to save in the above mentioned default directory. Afterwards, when you want to list all the files available in that directory, you should call,
private ArrayList<String> fileNames() {
ArrayList<String> namesArray = new ArrayList<>();
File[] arrayFiles = directoryDefault.listFiles();
for (File file : arrayFiles) {
namesArray.add(file.getName());
}
return namesArray;
}
I have use File delete to delete a file in my local folder however upon executing the line, it doesn't delete right away instead it delete right after I end my application or an error occurs.
After executing the delete line i.e myfile.delete(), the file in my local folder is unable to delete manually as it appear to be used by some other application.
Is there other way that I can delete the file immediately?
String localFilePath = "C:\\Desktop\\smefile.txt";
File file = new File(localFilePath);
if(file.delete()){
System.out.prinln("success");
}
else{
System.out.println("failure");
}
You must be using that file somewhere in your application.
An open file can't be deleted.
You can try using windows way to delete a file using below method
Runtime.getRuntime().exec(new String[]{"del", "C:\Desktop\smefile.txt"})
If you are even unable to delete that file using above method, its sure that you have opened that file somewhere in your application.
you can also try this Files.delete(path);
try {
Files.delete(localFilePath);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
I'm needing to open a folder containing the specified file, and highlight this said file. I have been looking for this for long but I have been unlucky. Could someone explain how this could be done using java?
Would be much appreciated. I am able to open files, folders, but not open the containing folder and highlighting a file. Cross platform code would be a plus, or just point me to the direction! Thanks!
#UPDATE:
Basically I'm doing an image sorter. I have a ArrayList containing filenames, e.g. myarraylist.get(0) would return funny_cat.jpg
This can be a handy functionality to have in a program that works with files/folders. It's easy enough to actually open the containing folder using:
I want the user to be able to open the currently selected item in a JList and open the containing folder with the target file selected.
I would post the code but it is too long and most unnecesary for this question, I will however post below how I open an explorer window, for the settings section of program, in order to choose a new directory to use:
public void browseFolder(){
System.out.println("browsing!");
final JFileChooser fc = new JFileChooser();
File dir = new File(core.Loader.path);
fc.setCurrentDirectory(dir);
// Windows and Mac OSX compatibility code
if (System.getProperty("os.name").startsWith("Mac OS X")) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
fc.setApproveButtonText("Choose directory");
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
// if the user accidently click a file, then select the parent directory.
if (!f.isDirectory()) {
f = f.getParentFile();
}
// debug
System.out.println("Selected directory for import " + f);
}
}
#UPDATE
I have found the solution, will post as answer below.
So, I just called this method from the action performed and it does the trick.
Basically, the solution was to make this terminal command:
open -R absolute/path/to/file.jpg
This is for Mac OS X only, below is my method I use:
public void openFileInFolder(String filename){
try {
Process ls_proc;
String mvnClean = "open -R " + core.Loader.path + "/" + file_chosen;
String OS = System.getProperty("os.name");
System.out.println("OS is: " + OS);
if (OS.contains("Windows")) {
//code ...
} else {
ls_proc = Runtime.getRuntime().exec(mvnClean);
}
} catch (Exception e){
System.err.println("exception");
}
}