I need to save something for every request in a log.txt file.
index.jsp in the below do that (which runs in localhost) correctly.
StringBuilder html = new StringBuilder();
ServletContext context = request.getServletContext();
String file = context.getRealPath("/");
html.append(html);
file += "log.txt";
System.out.println(file);
html.append("<br/>\n____________________________________<br/>\n");//file path
html.append(file.toString());//file path
html.append("<br/>\n____________________________________<br/>\n");//file path
FileWriter filewriter = new FileWriter(file, true);
filewriter.write(html.toString());
filewriter.close();
But when i push my project in Openshift it return null as file path:
I create log.txt manually and set 777 for its permission near index.jsp but it is always empty!!
According to the developer center [1] you should use the data folder if you want to have persistent storage of your uploaded/dynamically created files. Or else they will be wiped every time you perform a git push.
Related
I am trying to write a Java code in my Spring MVC Web Application that will create a file and save the file to a local directory. My code is as follows:
String fileName = new SimpleDateFormat("yyyyMMddHHmmss'.csv'").format(new Date());
File file = new File("C:\\my-files\\"+fileName);
FileWriter writer = new FileWriter(file);
for (Obj obj : objList)
{
StringBuilder sb = new StringBuilder();
sb.append(DATA);
writer.write(sb.toString());
writer.flush();
writer.write("\r\n");
}
writer.close();
This code works for me when I run locally. But when I try to run this code from the server, the file is not getting created. I am not sure if I should be setting some permissions for writing file when the code is run from a server.
I want the file to be created and downloaded to the local drive of the computer from which the web application is accessed. I dont want the file to be saved anywhere else
You have to check if the servers harddrive is also called C:\ and if the directory my-files exists...
I would generally recommend using relative paths
File file = new File(fileName);
Or create your own directory and also use relative paths
File file = new File("mydir");
if(!file.exists()) {
file.mkdir();
}
file = new File(fileName);
... rest of your code
I am trying to create a temp file in a specific folder
In the image below, you can find the structure tree of my project. I am currently in FileAnalyse.java and trying to create the file in data, under webcontent.
The following tries did not work for me:
File dir = new File(System.getProperty("user.dir")+"/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
or
File dir = new File("/WebContent/data");
File subjectFile = File.createTempFile("subjects", ".json",dir);
File dir = new File("WebContent/data");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
File subjectFile = File.createTempFile("subjects", ".json",dir);
This worked for me
note:
Your Version:
File dir = new File("/WebContent/data"); //has a / before WebContent
Correct Version:
File dir = new File("WebContent/data"); // no / before WebContent
Edit:
You can check if your path is the correct one with your attempts (or if you're on the right track to get the correct) when you print out the Path you're currently working with:
File dir = new File("YOUR/ATTEMPT");
System.out.println(dir.getAbsolutePath()); //check the path with System.out
that way you can check the absolute path, and you can look if the current attempted Pathstring is nearly correct
I solved the problem by changing the working directory of eclipse by going to run configurations->tomcat->change working directory
I want to read a file from directory.File is in root directory. If i use path as E:\Java\Netbeans_practice\project_141\Description.txt then it works fine.But when i wanted to use path as the file name or within a defined folder as Info\Description.txt , it gives error (java.io.FileNotFoundException: Description.txt (The system cannot find the file specified)). Actually i don't want to use the path name before project directory (ex: E:\Java\Netbeans_practice\project_141).I have searched a lot but unable to solve.Please help me. Here is my portion of code :
Scanner in = new Scanner(new FileReader("Description.txt");
while(in.hasNextLine()){
out.print("* "+in.nextLine()+"<br>");
}
When you deploy your web app, only the contents inside the "WebContent" will be deployed. You can verify this by going to (assuming you are using tomcat in your eclipse):
projectworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\<contextName>
So you may wanan copy your "Description.txt" file into "/WEB-INF" (for security sake) directory. Then you should be able to access it:
File file = new File(getServletContext().getRealPath("/WEB-INF/Description.txt"));
Update:
String path="/WEB-INF/Description.txt";
InputStream inputStream = this.getServletConfig().getServletContext().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I need to create temporary directory but I'm always getting access denied when I try to create a file into the temporary directory.
java.io.FileNotFoundException: C:\tmpDir7504230706415790917 (Access Denied)
here's my code:
public static File createTempDir() throws IOException {
File temp = File.createTempFile("tmpDir", "", new File("C:/"));
temp.delete();
temp.mkdir();
return temp;
}
public File createFile(InputStream inputStream, File tmpDir ) {
File file = null;
if (tmpDir.isDirectory()) {
try {
file = new File(tmpDir.getAbsolutePath());
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return file;
}
I'm working on a web application and I'm using tomcat. Is there a way to create temporary file on tomcat server memory? I know that's bizarre, but I don't know ... maybe it's possible.
You could use Tomcat's temp folder.
If you use
<%=System.getProperty("java.io.tmpdir")%>
in a JSP you can get path to it.
This line in your code says create a file whose name starts with text "tmpDir" in the directory "C:\". That is not what you want.
File temp = File.createTempFile("tmpDir","",new File("C:/"));
The operating system is properly disallowing that because C:\ is a protected directory. Use the following instead:
File temp = File.createTempFile("tmp",null);
This will let Java determine the appropriate temporary directory. Your file will have the simple prefix "tmp" followed by some random text. You can change "tmp" to anything meaningful for your app, in case you need to manually clean out these temp files and you want to be able to quickly identify them.
You usually cannot write onto C:\ directly due to the default permission setting. I sometime have permission issue for doing so. However, you can write your temporary file in your user folder. Usually, this is C:\Documents and Settings\UserName\ on XP or C:\Users\UserName\ on vista and Windows 7. A tool called SystemUtils from Apache Lang can be very useful if you want to get the home directory depending on OS platform.
For example:
SystemUtils.getUserDir();
SystemUtils.getUserHome();
Update
Also, you create a temp file object but you call mkdir to make it into a directory and try to write your file to that directory object. You can only write a file into a directory but not on the directory itself. To solve this problem, either don't call temp.mkdir(); or change this file=new File(tmpDir.getAbsolutePath()); to file=new File(tmpDir, "sometempname");
On Linux with tomcat7 installation:
So if you are running web application this is the temp directory Tomcat uses for the creation of temporary files.
TOMCAT_HOME/temp
In my case TOMCAT_HOME => /usr/share/tomcat7
If you are running Java program without tomcat, by default it uses /tmp directory.
Not sure if it affects but i ran this command too.
chmod 777 on TOMCAT_HOME/temp