File get save under some Unknown Path in Eclipse - java

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");

Related

URI not hierarchical need to use File class for a method

I need to open a video file with my code, and it works perfectly fine in Eclipse but when I export into a runnable JAR, i get an error "URI not hierarchical".
I have seen people suggest using getResourceAsStream(), but i need to have a file object as i am using Desktop.getDesktop.open(File). Can anyone help me out?
Here is the code:
try {
URI path1 = getClass().getResource("/videos/tutorialVid1.mp4").toURI();
File f = new File(path1);
Desktop.getDesktop().open(f);
} catch (Exception e) {
e.printStackTrace();
}
if it helps my folder list is like
Src
videos
videoFile.mp4
EDIT:
I plan to run this on windows only, and use launch4j to create an exe.
You can copy the file from the jar to a temporary file and open that.
Here's a method to create a temporary file for a given jar resource:
public static File createTempFile(String path) {
String[] parts = path.split("/");
File f = File.createTempFile(parts[parts.length - 1], ".tmp");
f.deleteOnExit();
try (Inputstream in = getClass().getResourceAsStream(path)) {
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
return f;
}
And here's an example of how you'd use it:
Desktop.getDesktop().open(createTempFile("/videos/tutorialVid1.mp4"));

How to get the absolute path of a file in my project (and not of a file stored in a temporary folder)

I am using:
Eclipse Java EE IDE for Web Developers version: Mars.2 Release (4.5.2);
Apache Tomcat v8.0;
a Web Dynamic project;
a Java Servlet.
I have a JSON file stored in the ./WebContent folder. I am trying to get the absolute path of the JSON file in this way:
ServletContext sc = request.getSession().getServletContext();
//String absolutePath = "/Users/kazuhira/Documents/MAC_workspace/lab2_calendario/WebContent/Database/Events.json";
String relativePath = "eventsBackup.json";
String filePath = sc.getRealPath(relativePath);
System.out.println("(saverServlet): the path of the file is "+filePath);
//System.out.println("(saverServlet): the path of the file is "+absolutePath);
//File file = new File(absolutePath);
String content = request.getParameter("jsonEventsArray");
try (FileOutputStream fop = new FileOutputStream(file)) {
System.out.println("(saverServlet): trying to access to the file"+filePath);
// if file doesn't exists, then create it
if (!file.exists()) {
System.out.println("(saverServlet): the file doesn't exists");
file.createNewFile();
System.out.println("(saverServlet): file "+filePath+" created");
}
System.out.println("(saverServlet): writing on the file "+filePath);
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("(saverServlet): events backup done");
} catch (IOException e) {
e.printStackTrace();
}
and the file path reconstructed from the relativePath is:
/Users/kazuhira/Documents/MAC_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/lab2_calendario/testJson.txt
Why String filePath = sc.getRealPath(relativePath); generates a path on a temporary folder? In which way I can configure the context on the "real" json file (the same I create in the project)?
I suppose Tomcat is working in a temporary context, why? There's a way to tell him to use the same folder of the project?
Yes, you can by changing an option in your Server configuration in Eclipse
Select the second option in the radio button list :)

Why can't I find my File?

I'm trying to open a CSV file name "logger.csv" which I have saved in the source folder itself.
public static void main(String[] args) {
String filename = "logger.csv";
File motor_readings = new File(filename);
try {
Scanner inputStream = new Scanner(motor_readings);
while (inputStream.hasNext()){
System.out.println(inputStream.next());
}
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Error: File not found!");
}
}
However, this keeps on giving me a "File not found" error.
If you use relative pathing as you are right now - the file needs to exist in the project root, not in the directory of the java file.
Consider this hierarchy:
project/
src/main/java
file.java
logger.csv
new File("logger.csv") will not work.
project/
logger.csv
src/main/java
file.java
new File("logger.csv") will now work. (notice, the file is adjacent to the src directory.)
Put the file on level up. In the main folder of the project.
To see where the file is expected update the code in your catch clause to:
System.out.println("Error: File not found: " + motor_readings.getAbsolutePath());
Put it there and be sure to refresh your workspace in Eclipse so that the file can be seen.

i want relative path for a file in java

I am new to java. I want to read a properties file in java. But i have my properties file in a different path in the same project.
I don't want to hard-code it. I want try with dynamic path.
Here is my code,
Properties properties = new Properties();
try{
File file = new File("myFile.properties");
FileInputStream fileInput = new FileInputStream(file);
properties.load(fileInput);
}catch(Exception ex)
{
System.err.println(ex.getMessage());
}
my file is in the folder, webapp/txt/myFile.properties.
Can any one help me in solving this issue?.
One way to solve this is split the absolute path to you file in two parts
Path till your project folder
path from you project folder onwards (Relative path)
You can tread these two properties in your application and concatenate and get the absolute path of the file. The relative path remains configurable.
public Properties loadDBProperties() {
InputStream dbPropInputStream = null;
dbPropInputStream = DbConnection.class
.getResourceAsStream("MyFile.properties");
dbProperties = new Properties();
try {
dbProperties.load(dbPropInputStream);
} catch (IOException ex) {
ex.printStackTrace();
}
return dbProperties;
}
you can call this method from
dbProperties = loadDBProperties();
String dbName = dbProperties.getProperty("db.schema");//you can read your line form here of properties file
if its under webapp/txt.myFile.properties and webapp is the public web space, then you need to read it using absolute URL
getServletContext().getRealpath("/txt/myFile.properties")
Properties prop=new Properties();
InputStream input = getServletContext().getResourceAsStream("/txt/myFile.properties");
prop.load(input);
System.out.println(prop.getProperty(<PROPERTY>));

set directory to a path in a file

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) {
}

Categories