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");
}
}
Related
In my Project, I want to open the windows file explorer with java, in which you can select a file or a folder and click the "OK" button. Now I want to have the path of the selected file in my Javacode.
Basically like the window which pops up in every standard texteditor after you hit the "OPEN" button to choose the file to open in the editor.
I know how to open the windows file explorer with Runtime.getRuntime().exec("explorer.exe") but I canĀ“t figure out a way to return the file path.
The best option is to use JFileChooser class in javax.swing.JFileChooser. It's a Java swing object so it won't invoke the native OS's file browser but it does a good job at selecting a file/saving to a location. Take a look at this link on basic implementation of it.
I used this method from the link in my code:
public static Path getInputPath(String s) {
/*Send a path (a String path) to open in a specific directory
or if null default directory */
JFileChooser jd = s == null ? new JFileChooser() : new JFileChooser(s);
jd.setDialogTitle("Choose input file");
int returnVal= jd.showOpenDialog(null);
/* If user didn't select a file and click ok, return null Path object*/
if (returnVal != JFileChooser.APPROVE_OPTION) return null;
return jd.getSelectedFile().toPath();
}
Note that this method returns a Path object, not a String path. This can be changed as needed.
This is how I'd use a JFileChooser for your problem:
String filePath; // File path plus name and file extension
String directory; // File directory
if (returnVal == JFileChooser.APPROVE_OPTION) {
directory = fc.getSelectedFile().getName();
} else {
directory = "Error in selection";
}
filePath = directory + "\\" + folderName;
I am trying to pass a path from Java's inbuilt file manager to ADB with java program on Linux to install apk on android device. When the code is executed the apk selected using file manager never gets installed.
Here is the code:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"APK Files", "apk");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You choose to open this file: " + chooser.getSelectedFile().getName());
File file = new File("");
System.out.println(file.getAbsolutePath().toString());
try {
Process p1 = Runtime.getRuntime().exec("adb kill-server"); //for killing old adb instance
Process p2 = Runtime.getRuntime().exec("adb start-server");
Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\"");
p3.waitFor();
Process p4 = Runtime.getRuntime().exec("adb kill-server");
} catch (Exception e1) {
System.err.println(e1);
}
The following code should install the apk:
Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\"");
I figured it out myself, and here is the code:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String filename = chooser.getSelectedFile().getName();
try {
String[] commands = new String[3];
commands[0] = "adb";
commands[1] = "install";
commands[2] = file.getAbsolutePath();
Process p1 = Runtime.getRuntime().exec(commands, null);
p1.waitFor();
} catch (Exception e1) {
System.err.println(e1);
}
}
Change the line
File file = new File("");
to
File file = chooser.getSelectedFile();
Also, don't forget to check
if(file.exists()) {
to validate the file.
I've spent a week working towards the same task for window system I have found out a simple solution to do this task, Here are some of the following steps that I have applied in my project
The First step is to download the ADB tool (Known as platform-tools) from this URL, and extract the downloaded file into your workspace directory.
Open the directory you downloaded the platform tools into
Create the Batch file if you don't aware how to create batch file follow the following steps
i. Open your text editor notepad or notepad++
ii. Save it as xyz.bat then it will be treated by the window system as a batch file
Open your batch file in your text editor and paste the following command
adb install "b2c.apk" && adb shell am start -n com.xyz.app/com.xyz.b2c.Activity.SplashScreen**
(Here there are two ADB command which separated by the ampersand sign.
The first command is for installing the APK in your Android devices
and the second one is to open the application )
i. b2c.apk is my android APK Which I want to install on my phone
ii. com.xyz.app is an android application package name and com.xyz.b2c.Activity.SplashScreen is an activity package name that I want to open
Save the file and close it, and then copy that file and paste it in the directory with the platform tools. And don't forget to place your APK file in this directory too
cd into the platform directory, and run this Java program:
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Scanner;
public class TestClass {
static int progress = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String ls_str;
Process p = Runtime.getRuntime().exec("cmd /c xyz.bat", null, new File("E:\\Arun_Java_Workspace\\TestApplication\\platform-tools"));
DataInputStream ls_in = new DataInputStream(
p.getInputStream());
while ((ls_str = ls_in.readLine()) != null) {
System.out.println(ls_str);
}
} catch (Exception e) {
System.out.println("Exception e: " + e);
}
}
}
I have a Java program that I am using to scan a directory to look for certain files. It finds the files but now I am trying to get the code to open the files once it finds them, but I am not sure how to do that.
Here a part of my code
File file = new File("/Users/******/Desktop/******");
String[] A = file.list();
File[] C = file.listFiles();
for (String string : A) {
if (string.endsWith(".txt")) {
System.out.println(string);
}
if (string.contains("******")) {
System.out.println("It contains X file");
}
}
I am trying to get it so once it finds the files ending in .txt, it opens all of them
I have tried using Google on how to solve his, I came across .getRuntime() and so I tried
try{
Runtime.getRuntime().exec("******.txt");
} catch(IOException e){
}
But I am not fully understanding how how this works. I am trying to get to so that once it finds the files it opens them. I am not trying to have the IDE open the text on the screen. I want the actual Notepad/TextEdit program to open.
File[] files = new File("/Users/******/Desktop/******").listFiles();
for (File f : files) {
String fileName = f.getName();
if (fileName.endsWith(".txt")) {
System.out.println(fileName);
}
if (fileName.contains("******")) {
System.out.println("It contains X file");
}
}
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.
i created an html editor and i want to get the file name & path of opened file in the JTextPane. any suggestion?
Assuming you make use of the File chooser (the file picker), which seems quite likely for a code editor you could simply save the file path you receive as a result:
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//At this point you can use: file.getName() to get your filename
//You can also use file.getPath()
} else {
//Canceled opening
}
}
}
You could save the result of file.getName() and file.getPath() to a string that you would assign to your JTextPane later on.
For additional information on file choosers see the documentation which also explains this process in more detail.
Should you be working with File you can make use of the same functions which will provide the same information.