jFilechooser show folder - java

I want to show the parent folder of current directory in jfilechooser.
I want to display that folder with .. which refers to the parent folder

Use the constructor which takes file path as argument like this.
JFileChooser jfc = new JFileChooser(".\\..");
Check out JFileChooser(File currentDirectory).

This is an "attempt" to implement the functionality that you request, the problem I have is that it's not possible replicate entirely what the system is doing.
Basically, the directory combo box is expecting some kind of native File object (in the case of Windows, a sun.awt.shell.Win32ShellFolder2). But there doesn't seem to be any way by which we can create them from within the provided API (and you won't want to create them manually, as it will break the Look and Feel and cross platform functionality).
import core.util.MethodInvoker;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import javax.swing.plaf.ComponentUI;
public class TestFileChooser {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
System.out.println(UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFileChooser fc = new JFileChooser(new MyFileSystemView());
fc.showOpenDialog(null);
}
});
}
public static class MyFileSystemView extends FileSystemView {
#Override
public File[] getFiles(File dir, boolean useFileHiding) {
File[] files = super.getFiles(dir, useFileHiding);
List<File> fileList = new ArrayList<>(Arrays.asList(files));
if (!isFileSystemRoot(dir)) {
File newPath = FileSystemView.getFileSystemView().createFileObject(dir, "/..");
fileList.add(0, newPath);
}
files = fileList.toArray(files);
return files;
}
#Override
public File createNewFolder(File containingDir) throws IOException {
File newFolder = new File(containingDir + File.separator + "New Folder");
if (!newFolder.mkdir()) {
newFolder = null;
}
return newFolder;
}
}
}

Related

Copying file using Apache Commons FileUtils

On the first run, I want to copy the given File to a new location with a new file name.
Every subsequent run should overwrite the same destination file created during first run.
During first run, the destination file does not exist. Only the directory exists.
I wrote the following program:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
However, this throws null pointer exception on the following line:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
What am I missing?
Directory someDir is directly under my project's root directory in eclipse.
Both source files myFile.txt and myFile_Another.txt exists directly under my project's root directory in eclipse.
I used this and it works as I am expecting:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
Using Java nio.

Copy all the files from a directory to another

i'm trying to copy all the files inside a directory to another(but i want it to not copy the folders). I'm trying to use Files.copy but i'm getting this error:
Exception in thread "main" java.nio.file.FileAlreadyExistsException:
Here's my actual code:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Exercici1 {
public static void copiarArchivos(String pathSource,String pathOutcome, String sufix) throws IOException {
File origen = new File(pathSource);
String[] contenidoOrigen = origen.list();
for(String string:contenidoOrigen){
File interno = new File(origen,string);
if (interno.isDirectory()){
copiarArchivos(interno.getPath(),pathOutcome,sufix);
} else {
Path targetOutcome = Paths.get(pathOutcome);
Path targetSource = Paths.get(interno.getPath());
Files.copy(targetSource,targetOutcome);
}
}
}
public static void main(String[] args) throws IOException {
copiarArchivos("Vampiro_Mascarada","pruebaPDF",".pdf");
}
}
My folder structure is like this:
/out
/pruebasPDF
/src
/Vampiro_Mascarada
/1.pdf
/2.pfdf
/Images
/1.png
/2.png
You need to use to Files.copy(source,dest,CopyOption) with the REPLACE_EXISTING option.

FileUtils.listFiles and IOFileFilter

Hi i want to recursively check if the files and subfolders of a certain directory contain a certain string so tried this
package com.tecsys.sm.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import com.tecsys.sm.util.WindowsDirectories;
public class ApacheListOfFiles {
public static void main(String[] args){
final String envName= "test_trunkcpsm";
WindowsDirectories wd = new WindowsDirectories();
File startPath = new File(wd.getStartMenuDir()+File.separator+"Programs");
Collection<File> listF = FileUtils.listFiles(startPath, new IOFileFilter() {
#Override
public boolean accept(File dir, String name) {
return false;
}
#Override
public boolean accept(File file) {
// TODO Auto-generated method stub
if(file.getName().contains(envName)){
System.out.println(file);
return true;
}else
return false;
}
},TrueFileFilter.INSTANCE);
System.out.println(listF.size());
Iterator<File> it = listF.iterator();
while(it.hasNext()){
System.out.println("Le fichier est : "+it.next());
}
}
}
The output of this is the following:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\TECSYS\iTopia Environments\test_trunkcpsm
0
So he finds the file i am searching for but still return an empty list, why is that ? And also while we are at it, when is the first accept called ? i have some difficulties understanding how this class works.
It works for me, may be the reason is false returned in the first accept().
You may also want to look at DelegateFileFilter to implement a single accept().
Or to use this single call for the job:
Collection listF = FileUtils.listFiles(
startPath, new WildcardFileFilter("*" + envName + "*"), TrueFileFilter.TRUE);

Adding methodName to selenium failed screenshot name using Java

I am trying to add the failed methodName to the screenshot that is taken when a failure occurs while running selenium using java. Ive tried multiple solutions around the net but they all wind up returning the methodName of the rule class or methodName. I am not sure how to make it so the screenshot file name returns 'shouldFail_date.png'.
package test;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ScreenShotRule extends TestWatcher {
private WebDriver browser;
public ScreenShotRule(WebDriver browser) {
this.browser = browser;
}
#Override
protected void failed(Throwable e, Description description) {
TakesScreenshot takesScreenshot = (TakesScreenshot) browser;
File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
File destFile = getDestinationFile();
try {
FileUtils.copyFile(scrFile, destFile);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
#Override
protected void finished(Description description) {
browser.close();
}
private File getDestinationFile() {
Throwable t = new Throwable();
String callerMethodName = t.getStackTrace()[1].getMethodName();
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy");
String userDirectory = "screenshots/" + dateFormat.format(new Date()) + "/";
new File(userDirectory).mkdirs();
String absoluteFileName = userDirectory callerMethodName + dateFormat.format(new Date()) + ".png";
return new File(absoluteFileName);
}
}
package test;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotTest {
private WebDriver browser = new FirefoxDriver();
#Rule
public ScreenShotRule screenShootRule = new ScreenShotRule(browser);
#Test
public void shouldFail() {
browser.get("http://www.google.com");
By link = By.partialLinkText("I do not expect to find a link with this text");
browser.findElement(link);
}
}
You can use one of the efficient selenium testing-frameworks - ISFW that is based on testng and provides descriptive reporting with the need you have. Here are some of the snapshots
Overview
Detail Report

How to download IntelliJ IDEA JavaBeans component of the JAR file

How to insert a palette component of the jar file?
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: user
* Date: 05.07.13
* Time: 17:51
* To change this template use File | Settings | File Templates.
*/
public class ImageViewerBean extends JLabel {
private File file=null;
int XPREFSIZE=200;
int YPREFSIZE=200;
public ImageViewerBean(){
setBorder(BorderFactory.createEtchedBorder());
}
public void setFileName(String fileName)
{
File file1=new File(fileName);
try {
setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
file=null;
setIcon(null);
}
}
public String getFileName(){
if (file!=null)
return file.getPath();
else
return null;
}
public Dimension getPreferredSize(){
return new Dimension(XPREFSIZE,YPREFSIZE);
}
}
Manifest:
Manifest-Version: 1.0
Name: C:\Users\user\IdeaProjects\AWTLearn\src\ImageViewerBean.java
Java-Bean: True
In the manifesto, all strictly no extra spaces at the end of an empty string.
Please check Adding GUI Components and Forms to the Palette on the IDEA web help page.

Categories

Resources