I just want to set the directory to a path I have written in a file before.
Therefore I used :
fileChooser.setCurrentDirectory(new File("path.txt"));
and in path.txt the path is given. But unfortunately this does not work out and I wonder why :P.
I think I got it all wrong with the setCurrentDic..
setCurrentDirectory takes a file representing a directory as parameter. Not a text file where a path is written.
To do what you want, you have to read the file "path.txt", create a File object with the contents that you just read, and pass this file to setCurrentDirectory :
String pathWrittenInTextFile = readFileAsString(new File("path.txt"));
File theDirectory = new File(pathWrittenInTextFile);
fileChooser.setCurrentDirectory(theDirectory);
You have to read the contents of path.txt. Thea easiest way is through commons-io:
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File dir = new File(fileContents);
You can also use FileUtils.readFileToString(..)
JFileChooser chooser = new JFileChooser();
try {
// Create a File object containing the canonical path of the
// desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e) {
}
Related
I am using Eclipse and have the following folder structure:
Eclipse Folder Structure
In UserHelper.java i have the code
try {
File file = new File ("vikvik1.JSON");
if (!file.exists ()) {
System.out.println ("No file");
file.createNewFile ();
temp = true;
}
System.out.println (file.getAbsolutePath ());
} catch (IOException ioe) {
System.out.println ("Exception occurred:");
ioe.printStackTrace ();
}
But after creating the file, the output is C:\Users\a595649\Documents\Vikram Thakur\Soft\eclipse\vikvik1.JSON
This is the location where my Eclipse Exe file is stored.
How can I get this File saved under my project DBnov folder ?
You have to provide the path of your file while instantiating the File object, otherwise java select it per default.
See the javadoc for the constructor, you can initiate it different ways, for example with the path as String:
File file = new File ("your_path", "vikvik1.JSON");
One possible solution:
create a property file under your classpath, say foo.properties
put there a property like
basePath=/some/path/you/want/to/use
Read the property file
String basePath="";
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
basePath=properties.getProperty("basePath");
}
Read your file
File file = new File ("basePath","vikvik1.JSON");
When a user clicks a button I would like to generate and add the file to the system clipboard. I have been able to do this, but when the file is added to the system clipboard, it also generates the file in the project folder (I'm using Eclipse). Can I make it directly on the system clipboard and not have it show up in a directory?
When I make a file, here is the code I use:
File file = new File("file.txt");
should "file.txt" be replaced with a path to the system clipboard? Or is that not possible?
StringSelection sel = new StringSelection(<insert string here>);
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
clip.setContents(sel, sel);
You can view this for string selection http://docs.oracle.com/javase/8/docs/api/java/awt/datatransfer/StringSelection.html
Do not create a file in the path of your project. You know that when you create file using the following statement:
File file = new File("file.txt");
It is being created near the class file of your code.
Just create a temp file using the createTempFile static method of class File :
try {
File f = File.createTempFile("file", ".txt");
FileWriter wr = new FileWriter(f);
wr.write("This is a Test!");
wr.close();
// Add it to clipboard here
} catch (IOException e) {
e.printStackTrace();
}
Good Luck
I have convert file into DBF format. But i must save that dbf file into specific folder which has generated when i create directory. The common coding just written like this
import java.io.File;
// demonstrates how to create a directory in java
public class JavaCreateDirectoryExample
{
public static void main(String[] args)
{
File dir = new File("/Users/al/tmp/TestDirectory");
// attempt to create the directory here
boolean successful = dir.mkdir();
if (successful)
{
// creating the directory succeeded
System.out.println("directory was created successfully");
}
else
{
// creating the directory failed
System.out.println("failed trying to create the directory");
}
}
}
But, i would like change "/Users/al/tmp/TestDirectory" into a dynamic state which i take it from the path JFileChooser that i've made. Is there any possibilities to make it done? Thanks a lot
If you want to use the same variable, you can instantiate it again.
File dir = new File("/Users/al/tmp/TestDirectory");
boolean successful = dir.mkdir();
// Here we assign a new value by calling the constructor
dir = new File("/Users/al/tmp/AnotherTestDirectory");
// Next we create the new directory using the same method
boolean successful2 = dir.mkdir();
I'm guessing your quite new to Java. You should get in the habit of reading the API. It is your friend and will help answer these questions.
The JFileChooser can be used to get the selected File which can be used to get the path
JFileChooser API:
getSelectedFile() - Returns the selected file.
File API:
getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
...and some sample code
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getAbsolutePath();
File dir = new File(path);
....
}
I have a java file path
/opt/test/myfolder/myinsidefolder/myfile.jar
I want to replace the file path to
here root path will remain same but want to change file name from myfile.jar to Test.xml
/opt/test/myfolder/myinsidefolder/Test.xml
How can i do this in java any help?
Using Java 9+
Path jarPath = Paths.get("/opt/test/myfolder/myinsidefolder/myfile.jar");
Path xmlPath = jarPath.resolveSibling("Test.xml");
Using Java 8 and older
File myfile = new File("/opt/.../myinsidefolder/myfile.jar");
File test = new File(myfile.getParent(), "Test.xml");
Or, if you prefer working with strings only:
String f = "/opt/test/myfolder/myinsidefolder/myfile.jar";
f = new File(new File(f).getParent(), "Test.xml").getAbsolutePath();
System.out.println(f); // /opt/test/myfolder/myinsidefolder/Test.xml
Check out the Java Commons IO FilenameUtils class.
That has numerous methods for reliably disassembling and manipulating filenames across different platforms (it's worth looking at for many other useful utilities too).
File f = new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File path = f.getParentFile();
File xml = new File(path, "Test.xml");
A more direct approach using only JRE available class File :
String parentPath = new File("/opt/test/myfolder/myinsidefolder/myfile.jar").getParent();
new File(parentPath, "Test.xml");
To rename the file you can use Files.move from java.nio.file.Files
File oldFile=new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File newFile=new File(oldFile.getParent+"/"+"Test.xml");
try
{
Files.move(oldFile.toPath(),newFile.toPath());
}
catch (IOException ex)
{
System.err.println("File was not renamed!");
}
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
String fileName = fc.getSelectedFile().getName();
String path = (new File(fileName)).getAbsolutePath();
}
The absolute path I get is the concatenation of the project directory and fileName!
JFileChooser.getSelectedFile() return the File object.
Why are you getting the file name and instantiating a new File object again?
Can you try:
fc.getSelectedFile().getAbsolutePath();
That's what getAbsolutePath() does - gets the full path, including drive letter (if you're on Windows), etc. What are you trying to get, just the file name?
After you initialize your File object, you can get just the file name from that, OR you can use JFileChooser.getSelectedFile()
If you're getting /path/to/filefilename but you're expecting /path/to/file/filename then you can add an extra slash to the path as appropriate.
Sure. Because you created new file new File(fileName) using returned filename, that means relative path. Use fc.getSelectedFile().getPath() or fc.getSelectedFile().getAbsolutePath() instead.