java: Open folder on button click - java

In java, how can we open a separate folder (e.g. c:) for user on click of a button, e.g like the way " locate this file on disk" or "open containing folder" does when we download a file and we want to know where it was saved. The goal is to save user's time to open a browser and locate the file on disk.
Thanks ( image below is an example from what firefox does)
I got the answer:
Here is what worked for me in Windows 7:
File foler = new File("C:\\"); // path to the directory to be opened
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
try {
desktop.open(foler);
} catch (IOException e) {
}
Thanks to #AlexS

I assume you have a file. With java.awt.Desktop you can use something like this:
public static void openContaiingFolder(File file) {
String absoluteFilePath = file.getAbsolutePath();
File folder = new File(absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf(File.separator)));
openFolder(folder);
}
public static void openFolder(File folder) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(folder);
}
}
Be awrae that if you call this with a File that is no directory at least Windows will try to open the file with the default program for the filetype.
But I don't know on which platforms this is supported.

Related

is it possible to read the downloaded file from chrome browser using selenium

I downloaded a text file by a click button functionality, using Selenium Java.
then the file is downloaded to a particular location in the system, for example,
C://myAppfiles.
But I can't access that downloaded folder because of some reason. But I have to read that file while downloading.
How to do it? is it possible to read that file from the browser(chrome) using selenium or any other method is available?
so I'd suggest to do the following:
wait until file download is done completely.
After that- try to list all the files in the given directory:
all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
That will help You to understand if there any files at all (in the given directory).
Dont forget to make paths platform independent (to the folder/ file), like:
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"myDownloadedFile.txt");
Also, You might want to check whether file actually exists via Path methods.
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
Path filePath= Paths.get("C:\\myAppfiles\\downloaded.txt");
System.out.println("if exists: " + Files.exists(firstPath));
}
}
Additionally, path suggests You to check some other options on the file:
The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.
Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
Files.isReadable(file) & Files.isExecutable(file);
Once You face any exception- feel free to post it here.
Hope this helps You

How to get files from a project folder

The folder is /src/img. I need to get all file names(png files) from img folder and all subfolders.I dont know the full path to the folder so i need only to focus the project resourse. I need them in array. Using Java8 and Eclipse Mars.
So far this works:
try {
Files.walk(Paths.get("/home/fixxxer/NetBeansProjects/Installer/src/img/")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
} catch (IOException ex) {
Logger.getLogger(InstallFrame.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that the folder need to be called like this:
/img cause it is inside the project
Thanks in advance :)
You can use relative paths.
Here, I am assuming that Installer is your project name. Otherwise, you can edit the relative path according to your project setup.
Files.walk(Paths.get(".//src//img//")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
If you place your file
test.png
under
/src/resources/org/example
you can access it from your class
org.example.InstallFrame
using
final URL resource = InstallFrame.class.getResource("test.png");
respectively
final InputStream resourceAsStream = InstallFrame.class.getResourceAsStream("test.png");
First find the base path and then use in your code
String basePath = ClassLoader.getSystemResource("").getPath();
//move basepath to the path where img directory
//present in your project using ".."
//like basepath = basepath+"..\\..\\img"+
Files.walk(Paths.get(testPath)).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});

FileDialog mock files

I am implementing an Applet which needs to access to file system and I need to show to user mock/fake files under mypc or userhome.
There is a way to do it using JFileChooser with FileSystemView:
This is a short example for Windows OS:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSystemView(new FileSystemView() {
#Override
public File createNewFolder(File containingDir) throws IOException {
//do something, not important here
return null;
}
#Override
public File[] getFiles(File dir, boolean useFileHiding) {
File[] files = super.getFiles(dir, useFileHiding);
// my pc -> desktop -> null
if (dir.getParentFile() == null
|| dir.getParentFile().getParentFile() != null) {
return files;
}
List<File> newFiles = new ArrayList(Arrays.asList(files));
newFiles.add(new File("Custom_File_1"));
newFiles.add(new File("Custom_File_2"));
return newFiles.toArray(new File[newFiles.size()]);
}
});
But the issue is that JFileChooser does not work properly on Mac OS. There is no ability to navigate into any subdirectory, move up from the current directory.
Here is a similar problem:
JFileChooser for directories on the Mac: how to make it not suck? (I switched off DIRECTORIES_ONLY mode, but it did not help)
Now I am trying to use FileDialog, but there is another problem:
I can not find a way to show mock/fake files under mypc or userhome (like FileSystemView).
The question is: Is there an ability to fix JFileChooser in MAC OS? Or add mock/fake files into specific directory using FileDialog?

Load file in different directory

I want to load xml configuration file located in different directory.
The location of the files is:
<location_dir>/jar_file.jar
<location_dir>/xml_file.xml
The files are located in different directories which are located into one main directory. The different part is that I want want to sue the same directory structure on many operating systems.
I managed to create this code:
public class SeparatorTest
{
private static SettingsDataObject settingsData;
public void loadXMLFile() throws JAXBException
{
try
{
// File location by default ../conf/xmlfile.xml
settingsData = unmarshal(".." + File.separator + "conf" + File.separator + "xmlfile.xml");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
I want to ask is this example universal for every OS?

Java: opening a resource (txt file) which is in a jar with OS standard application

i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()

Categories

Resources