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)
Related
I've a web application on Tomcat 7.0.57 on Windows 8.1 running it as a service, that is instructed to copy a file on a locally network shared directory, for example \\Network_machine\Shared_folder, but it's not able to do so.
I am able to access the shared folder in windows explorer without any authentication, as it has permission to read for everyone. The following code is checking for the directory exist:
String sourceURL = this.servletContext.getInitParameter("sourceURL");
log.debug("---------->Source reports directory : " + sourceURL);
File sourceDir = new File(sourceURL);
log.debug("---------->Source directory exists : "+sourceDir.exists());
if (sourceDir.exists()) {
String files[] = sourceDir.list();
log.debug("----------> Total files in source dir :" + files.length);
List<String> newFiles = new ArrayList<String>(Arrays.asList(files));
newFiles.removeAll(processedFiles);
log.debug("----------> Latest files in source dir :" + newFiles.size());
File file = null;
if (newFiles.size() > 0) {
for (String fileName : newFiles) {
file = new File(sourceURL + Constants.FILE_SEP + fileName);
latestSourceFiles.add(file);
}
}
} else {
log.debug("Source reports directory " + sourceURL + " is not found");
}
Additional Info:
log - Source directory exists is returning 'FALSE'.
As Kenneth says, you need to map the shared folder to a drive and then write directly to that drive.
http://windows.microsoft.com/en-us/windows/create-shortcut-map-network-drive
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
I am developing and application using eclipse IDE. My application has a file upload functionality.
I am able to achieve how to upload the file and also to save it. But the problem is that the file uploaded didn't get store to my dynamic web project directory.
The file uploaded get store to my server directory with .metadata folder having path
file:///E:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/
I want to store my uploaded folder to my Webcontent folder having upload folder having images folder like WebContent/upload/images.
No doubt I am able to view the image file but, the path i want is like above only.
below code I am using to store the uploaded file
#RequestMapping(value = "/company/UploadFile.action", method = RequestMethod.POST)
public #ResponseBody String uploadFile(FileUploadBean uploadItem, BindingResult result,HttpServletRequest request, HttpServletResponse response) {
System.out.println("FILE UPLOAD ITEM SI SSLSL ::"+uploadItem);
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}
//set extjs return - error
extjsFormResult.setSuccess(false);
return extjsFormResult.toString();
}
// Some type of file processing...
System.err.println("-------------------------------------------");
System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
System.err.println("-------------------------------------------");
try{
MultipartFile file = uploadItem.getFile();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
/*if (file.getSize() > 10000) {
System.out.println("File Size:::" + file.getSize());
extjsFormResult.setSuccess(false);
return extjsFormResult.toString();
}*/
System.out.println("also path ::"+request.getRealPath("") + "/upload/images/");
System.out.println("PATHI SIS SIS"+this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println("size::" + file.getSize());
InetAddress addr = InetAddress.getLocalHost();
byte[] ipAddr = addr.getAddress();
System.out.println("HOST NAME"+request.getRealPath("ResourceMgt"));
System.out.println("HOST ADDR"+addr.getHostAddress());
System.out.println("HOST "+request.getRequestURI());
System.out.println("HOST "+request.getRequestURL());
fileName = request.getRealPath("") + "/upload/images/"
+ file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("FILEN ANEM AND PATH IS ::"+fileName);
System.out.println("fileName:" + file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[40000];
while ((readBytes = inputStream.read(buffer, 0, 40000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
companyservice.saveImages(file.getOriginalFilename(),fileName);
outputStream.close();
inputStream.close();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//set extjs return - sucsess
extjsFormResult.setSuccess(true);
return extjsFormResult.toString();
}
please suggest me how can I store the file uploaded to my WebContent having upload folder with images folder. My above code is working perfectly Just there is some issue with specifying the path.
Have you tried to change the destination of the outputStream?
fileName = request.getRealPath("") + "/upload/images/"
+ file.getOriginalFilename();
Instead of request.getRealPath("") put an absolute destination or play with ClassPath. For example:
fileName = "/opt/tomcat/webapps/upload/images/"
+ file.getOriginalFilename();
forum member
now I am able to upload the file successfully, but the file get stored to the deployed directory on the server.
As soon as I remove the project and redeployed the project to my Tomcat server 6.0 all the files I had uploaded gets deleted from that.
I am using JAVA as my server side technology with Tomcat server 6.0.
I am able to upload the file successfully, but the file get stored to the deployed directory on the server.
As soon as I remove the project and redeployed the project to my Tomcat server 7.0 all the files I had uploaded gets deleted from that.
I am using JAVA and JSF as my server side technology with Tomcat server 7.0 in Eclipse IDE
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.
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("/");