how do i create http visible files from java web application? - java

How can I create files visible by http protocol from java web application in web/myFiles folder ?
Is this even possible ?
for the following code :
String realPath = getServletContext().getRealPath("/");
System.out.println(realPath);
try {
BufferedWriter out = new BufferedWriter(new FileWriter( realPath + "\\myFiles\\test.txt"));
out.write("aString\nthis is a\nttest");
out.close();
} catch (IOException e) {
System.out.println("Exception " + e);
}
i keep getting the error :
Exception java.io.FileNotFoundException: C:\Documents and Settings\Andrei\My Documents\NetBeansProjects\SemanticCashUpV1.0\build\web\myFiles\test.txt (The system cannot find the path specified)

Yes possible,
You need to create file in public web area.
near to WEB-INF Dir.
you can get path to public web space by
request.getServletContext().getRealPath("/");

Related

Issue while moving file using java.nio

Getting below exception while trying to move a file after renaming it, issue is that it is occurring intermittently i.e. sometimes the code works and sometimes it does not and is not replicable, would be helpful if anyone can provide insight on the same
Caused by: java.nio.file.AccessDeniedException: /data/Inprocess/DEMO.20191026.csv -> /data/Inprocess/DEMO.20191026.csv.inprogress
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:457)
at sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:262)
at java.nio.file.Files.move(Files.java:1395)
Path fromPath = inputFile.toPath();
Path toPath = new File(inputFile.getAbsolutePath() + ".inprogress").toPath();
LOGGER.info("Moving file to Path: " + inputFile.getAbsolutePath() + ".inprogress");
try {
Files.move(fromPath, fromPath.resolveSibling(toPath),StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Handle Exception
throw new TradeProcessorException("Error while marking file Inprogress: ", e);
}
One difference between the old File (pure disk files/directories) and the newer, more powerful Path is, that the latter maintains its "file" system (which could be a zip, ram disk, remote disk). So once using Path, keep using it.
Path fromPath = inputFile.toPath();
String toName = inputFile.getFileName().toString() + ".inprogress";
Path toPath = inputFile.resolveSibling(toName);
LOGGER.info("Moving file to Path: " + toPath);
try {
Files.move(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING);
Your usage of resolveSibling seems to add a full path.
(Above the superfluous .toString() is just a reminder that getFileName() returns a Path.)

Error in file is :- java.io.FileNotFoundException: \files\storetime.txt (The system cannot find the path specified)

i am using eclipse for develop the java desktop application and working with file but got the above error
my code is as following please try to help me how to give path in eclipse and also get same problem to load image from the given task
i have put the "files" folder out side the "src" folder
how to give path dynamically
my code is ass following
public int getTimeId()
{
LOG.info("The File name is :- " + fileName);
LOG.info("The path is :- ");
int count=0;
FileInputStream fileInputStream;
ObjectInputStream objectInputStream;
try
{
fileInputStream=new FileInputStream("/files/storetime.txt");
objectInputStream=new ObjectInputStream(fileInputStream);
while(objectInputStream.readObject()!=null)
{
count++;
}
}
catch(IOException e)
{
System.out.println("Error in file is :- " + e);
} catch (ClassNotFoundException e) {
System.out.println("Error in class not found :- " + e);
}
return count;
}
}
You are providing the absolute path by prep-ending / in the path. It means root directory in Unix file system. so, you have to give a relative path of the file from the current directory.You can put files directory in the root directory of your project folder and use
fileInputStream=new FileInputStream("files/storetime.txt");
So, it will be picked up
Use FileInputStream(new File("files/storetime.txt")); don't use /file -> it will check for /file partition in linux as /root

Using the FileWriter with a full path

I specified the full path of the file location when I created a FileWriter, but I did not see the file being created. I also did not get any error during file creation.
Here's a snippet of my code:
public void writeToFile(String fullpath, String contents) {
File file = new File(fullpath, "contents.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
bw.write(contents);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
fullpath is "D:/codes/sources/logs/../../bin/logs".
I have searched my whole directory, but I cannot find the file anywhere.
If I specify just the filename only [File file = new File("contents.txt");] , it is able to save the contents of the file, but it is not placed on my preferred location.
How can I save the file content to a preferred location?
UPDATE:
I printed the full path using file.getAbsolutePath(), and I am getting the correct directory path. [D:\codes\sources\logs....\bin\logs\contents.txt] But when I look for the file in directory, I cannot find it there.
Make sure you add trailing backslashes to the path parameter so the path is recognized as a directory. The example provide is for a Windows OS which uses backslashes that are escaped. For a more robust method use the file.separator property for the system.
Works
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development\\",
"this is a test");
Doesn't Work
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development",
"this is a test");
File Separator Example
String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
+ "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");

Property file path Eclipse vs Deployed Java Web App

I'm maintaining properties files containing database credentials in protected folders on our internal server for each app that I deploy. I'm not allowed to store the credentials within the WAR file.
When testing on my PC the path is a windows mount, but when I depoloy to the server it is a unix path
I have been handling the retreival as such
//siteDbCedentialFolder obtained from web.xml
Properties prop = new Properties();
InputStream in = null;
try {
//assume running on server first
in = new FileInputStream("/abc/data/" + siteDbCedentialFolder + "/props.txt");
} catch (java.io.IOException ex) {
// Probabaly Running locally
in = new FileInputStream("W:/internal/abc/data/" + siteDbCedentialFolder + "/props.txt");
} catch (Exception xx) {
xx.printStackTrace();
}
prop.load(in);
in.close();
is my approach to use a catch to get the local path OK or is there a better way to code this?
Better way is to put the txt file in user home directory and get it by
System.getProperty("user.home");
and to get the full path
String pathToFile = System.getProperty("user.home") + File.separator + "data" + File.separator + "props.txt";
It would work across all the platform, provided that you need to put the file at proper place (user home)

Can't load Properties from JAR

For a few days now, I have been trying to get my Java project to load some properties from a file located in it's JAR file. However, I am constantly getting a null pointer when trying to load in the file.
The folder hierarchy has the properties file in /data, and all the source files in /emp/**/** ...
Code
Properties defaultProps = new Properties();
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("data/build_info.properties");
//InputStream in = new URL("file:data/build_info.properties").openStream();
defaultProps.load(in);
in.close();
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
} catch (NullPointerException e){
Log.E("NPE- Properties not loaded", "properties");
revision = "Properties file not found";
}
if (defaultProps.getProperty("build.major.number") == null) {
Log.W("Properties not loaded", "properties");
revision = "Properties file not found";
} else {
Log.V("Properties Loaded Successfully", "properties");
revision = "Version: " + defaultProps.getProperty("build.major.number")
+ "." + defaultProps.getProperty("build.minor.number") + " "
+ "Revision: "
+ defaultProps.getProperty("build.revision.number");
}
If data is in the root of your jar, and if build_info.properties is inside the data directory in the jar, and if the jar is on the classpath, then getClass().getClassLoader().getResourceAsStream("data/build_info.properties"); will find that properties file. You could also use getClass().getResourceAsStream("/data/build_info.properties");.
Peculiarities can arise if getClass() returns a class loaded by a classloader different than the one that has your jar on its classpath.
You could alternatively try --
Thread.currentThread().getContextClassLoader().getResourceAsStream("data/build_info.properties");
I had the same issue with a dead-simple console application. Eventually I found a hint at https://stackoverflow.com/a/1464541/1792291 and I made my console app into a swing app, and suddenly everything worked.
The explanation in the link above does make some sense: since the console app gets its properties (including CLASSPATH) once when the shell is created, it won't know about the classpath defined during/for/by the JVM.

Categories