问题
we are using a java library inside a web application which is hosted in apache server.ReadConfFile method in library returns file not found error.The method is as follows
public byte[] ReadConfFile()
{
try
{
File file = new File("/home/product/api/conf.txt");
if(!file.exists())
return "file not found".getBytes();
byte[] buf = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(buf);
return buf;
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
Is local file system access from web application allowed?. If yes , then is there any access permission that has to be set?
回答1:
To quickly answer your question: You can access the file system from a web application, but you would have to check your application server / web container on how to configure the SecurityManager (if one is installed).
However, your method of reading the file has severe issues which you should adress:
Do not check
if(!file.exists())
better checkif(!file.isFile())
. The first check also returns true if the file is a directory.If there is not a file, better not return a String, throw an Exception, or load some default Configuration or do something else which is useful.
Your logic for reading the file is very bad. If the read function returns a different amount of available bytes (maybe the read is chunked), you'll get a corrupt result.
You do not close the stream in a finally block, (or use a try with resources if you are using Java 7).
The exception handling is also not good. Printing the stacktrace is not good, logging it would be better. Handling the exception would be best (throw an exception, or switch to some default configuration, like when the file was not there).
Edit: If you want to access the client's file system, then this cannot be done from your web application running on the server directly. This of course would have to be done from code running on the client and you would have to fill in more details on what is running on the client side, since a "standard" web application would have Javascript and (X)HTML on the client, not java.
来源:https://stackoverflow.com/questions/19972243/accessing-linux-local-file-system-from-java-web-application