I am unable to create and then write a file in Tomcat. The file gets created if I run the java program (only the writing piece of code) as a Java application, but fails in Tomcat.
there is no error message. The file is simply not created at all!
Please suggest if I am missing something here:
//code inside the servlet
public void setData(HttpServletRequest request){
name=request.getParameter("name");
address=request.getParameter("address");
BufferedWriter dataOut;
try {
System.out.println("Wrinting file...");
dataOut = new BufferedWriter(new FileWriter("data.txt", true));
dataOut.write("name:");
dataOut.flush();
dataOut.write("address");
dataOut.flush();
dataOut.write("\n");
dataOut.flush();
dataOut.close();
System.out.println("File write complete!");
}
catch(Exception e){
e.printStackTrace();
}
Looks like the file really is created without problems.
You may actually be missing where it is saved.
Change this line:
System.out.println("File write complete!");
To:
System.out.println("File write complete! Saved to: "+new File("data.txt").getAbsolutePath());
And you may solve the mistery.
The file is being created, but it is using a relative path. It will be created relative to the execution location, which on Tomcat will not be where you're used to it being.
Use an absolute path or print its location.
Related
I had some new code using the commons-io FileUtils.openOutputStream(File) method, for a file that doesn't exist at the point of the call. This was failing with a "FileNotFoundException". I first thought this was a bug in commons-io, but then I realized that it's just calling "new FileOutputStream(file, append)", which is also supposed to create the file if it doesn't exist.
I then added code right before my call to FileUtils.openOutputStream(File) like the following:
if (!file.exists()) {
logger.info("Parent file exists: " + file.getParentFile().exists());
try {
file.createNewFile();
}
catch (Exception ex) {
logger.error("Creating file failed", ex);
}
}
This prints "true" for the parent file, and then "java.io.IOException: The system cannot find the path specified". I googled for this situation, and some people were hitting this if they went past the supposed 260 character limit for a file path on Windows. I thought that might be relevant, but my file path is only 230 characters long.
I also tried an experiment of trying to "touch" the same file path in my Cygwin bash shell, and it had no trouble doing that.
Update:
So I took the partial advice of trying to use Paths & Files to do this instead of just "File". My incoming parameter is a "File", so I can't do anything about that. I added the following code:
try {
Path path = Paths.get(file.getAbsolutePath()).toAbsolutePath();
if (!Files.exists(path.getParent())) {
Files.createDirectories(path);
}
file = Files.createFile(path).toFile();
}
catch (Exception ex) {
logger.error("Failed to create file");
}
What's curious is that this doesn't give me a better error message. In fact, it doesn't give me any error message, because it doesn't fail. It appears that NIO is taking a very different path to creating the file than the regular File object.
Update:
What is now working fine is the following:
file = Paths.get(file.getAbsolutePath()).toAbsolutePath().toFile();
try {
Path path = file.toPath();
if (!Files.exists(path.getParent())) {
Files.createDirectories(path);
}
if (!file.exists()) {
file = Files.createFile(path).toFile();
}
}
catch (Exception ex) {
logger.error("Failed to create file");
}
What's curious is that I should be able to remove that first line, which is essentially converting a relative path to an absolute path. My test run creates 50 or so files in the process. I tried commenting out that line and then clearing out my output tree and running the test. It got the following exception attempting to create the first file:
java.nio.file.AccessDeniedException: build\gen1\org\opendaylight\yang\gen\v1\urn\opendaylight\params\xml\ns\yang\pcep\types\rev131005\vs\tlv\vs\tlv\VendorPayload.java
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
What the heck?
Also note that I never did remove the older code that uses "File.createNewFile()", I just put the "Files" code before that, and the old code checks for "!file.exists()", so theoretically the old code would only execute if the new code somehow didn't create the file. On this first file, since the NIO creation failed, the file still didn't exist, and it went through the old creation code, which SUCCEEDED.
And even stranger, I let the test case run to the next file, and that failed in the NEW code with:
java.nio.file.FileAlreadyExistsException: build\gen1\org\opendaylight\yang\gen\v1\urn\opendaylight\params\xml\ns\yang\pcep\types\rev131005\vs\tlv\VsTlv.java
Note that the only way that block could have gotten that exception is if it executed the "Files.createFile(path).toFile()" line, and the only way it could have gotten to that line is if "!file.exists()" was TRUE, which means that the file did not exist. my brain is starting to melt. Also note that while I'm sitting at this breakpoint, I examined the file system, and that file does not exist.
This is 2015 and you say that you use Java 7.
Don't use File. Use this instead:
final Path path = Paths.get("....").toAbsolutePath();
// use Files.exists(path.getParent()) to check for the existence;
// if it doesn't exist use Files.createDirectories() on it
Files.createFile(thePath);
If the operation fails, you will at least get a meaningful exception telling you why it fails.
This is 2015. Drop. File. Now.
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'm simply trying to add a new line of text to my *.txt file, but nothing happens at all. The file is packed with a .war, so I use a ClassLoader to access the file. Also, both my eclipse IDE, and the contents of the file, use UTF-8 encoding.
I've used these for inspiration:
How to add a new line of text to an existing file in Java?
Java BufferedWriter object with utf-8
Now my code is mainly based on the last post, and looks like this:
public class test {
public static void main(String[] args){
URL url = Thread.currentThread().getContextClassLoader().getResource("MilestoneExport.txt");
File file = new File(url.getFile());
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've confirmed that the file is in fact found, and it reads fine. I've been able to output the entire content of it to the console through the use of a BufferedReader. The path of the file is also correct, but absolutely no text is added to the file. I've made sure that I have refreshed and updated every time I've run the program.
Also, I've tried to create a simple empty file called foo.txt, which is located in the same directory as test.java. I added the following code to the main method, as provided by the BufferedWriter API, at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
PrintWriter out2 = new PrintWriter(
new BufferedWriter(new FileWriter("foo.txt")));
out2.println("new Line");
out2.close();
What am i missing here? Why are there no error messages, and no responses or feedbacks whatsoever?
EVERYTHING BELOW IS ONLY ADDITIONAL INFO ABOUT WHAT I'VE TRIED. NO FEEDBACK IN ANY CASES:
Not this one: Why is BufferedWriter not writing to file?
Not this one: why is bufferedwriter not writing in the file?
Not this one: Unable to write to file using BufferedWriter
Yet another "remember to close/flush": Java : Problems accessing and writing to file
Defining the BufferedWriter outside the try block makes no difference, but I tried it anyway, due to How to write detail into file using BufferedWriter and FileWriter in Java?
Also, this code, from this answer, does nothing as well...
try {
BufferedWriter output = new BufferedWriter(new FileWriter(new File("house.txt")));
output.write("text");
output.close();
}
catch (IOException e) {
e.printStackTrace();
}
last but not least, I suspected that it might have something to do with the packaging of my Web-App, and differences between the source and target-folders. So I copied the code to a brand new clean project, but it still does nothing at all...
EDIT:
this code:
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getName());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.setLastModified(new GregorianCalendar().getTimeInMillis()));
gives these outputs:
true
D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
MilestoneExport.txt
false
true
true
Am I completely misunderstanding the use of java's File-objects, and it's uses with FileWriters? The file is clearly 100% confirmed the correct file.
You should use the other constructor of FileOutputStream in order to open the file in append mode :
FileOutputStream(File file, boolean append)
I.e,
new FileOutputStream(file, true)
Since I can't comment, you might not be saving the file back into the archive it came from (I'm not sure if java supports writing to the internal structures of archives by editing the files that are included, however you might want to try to store the file externally to the archive to see if that is the place the issue comes from).
The cause of what you posted in the comments is that your IDE won't extract the resource file from a compiled program, if you want to sync the internal data you might be able to setup a client-server connection using sockets and creating a program that writes the data to the local file from data packets send to your web-app, otherwise retrieving the edited file from where you are hosting might be less complicated (or if you are deploying from the same PC you might be able to get away with a symbolic or hard link)
I've tried this code that is very similar to yours and it's working nicely,
so i think the problem is the way you are picking the path of the file.
public static void main(String[] args){
File file = new File("./localtest.txt");
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
this works
PrintWriter pw= new PrintWriter(
new BufferedWriter(new FileWriter("C:\\foo.txt")));
pw.println("line 1");
pw.close();
I am trying to open a file i just created in my code (so i am sure that the file exists)
The code is like this:
File file = new File(filename);
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
...
bw.close();
try {
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
desktop.open(file);
} catch (Exception e) {
...
}
But as the title says i get a "java.io.IOException: The system cannot find the path specified" from the desktop.open(file) istruction.
The problem surely is that the file pathname contains spaces (which are translated into "%20"). Is there a way to avoid this?
I found the real problem.
It wasn't either the %20 as i supposed.
I just hadn't the privileges to directly access the file location. It's a bit complicated to explain...
i'm just sorry i coulnd't figure out the real problem before.
Thanks for your suggestions anyway!
Are you using an IDE? What is inside the variable 'filename' (it's actual contents). Line two is unnecessary.
Is the error from the stack trace pointing to BufferedWriter bw = new BufferedWriter(new FileWriter(file)); or desktop.open(file);
EDIT:
You can also try the following code
File myCSVFile; //reference to your csv file here
String execString = "excel " + myCSVFile.getAbsolutePath();
Runtime run = Runtime.getRuntime();
try {
Process pp = run.exec(execString);
} catch(Exception e) {
e.printStackTrace();
}
The java.io error is appearing because it's failing to open the file. The code above will force excel open with your file as the argument. You'll need to set your environment variable to ensure that the command 'excel' in the command line opens the Excel application.
If you're planning on releasing this application for use you can ensure that excel is installed by checking the registry, then checking the install location of Excel from there.
Try to open a different file with other applications and see if other file types are supported. As Clarisse said, IOException is thrown from the 'open' method if the specified file has no associated application or the associated application fails to be launched. If the specified file doesn't exists IllegalArgumentException is thrown, which is not in your case. If for some reason opening a CSV file with Desktop doesn't work for you, try using krslynx approach. Same can be found here. You can quickly assemble a test application for opening anything on your machine using the code found here
In the Desktop javadoc it's written :
IOException - if the specified file has no associated application or the associated application fails to be launched
So are you sure your filetype has a default application associated ?
As krslynx says, file.createNewFile() is unnecessary. However file.mkdirs() may be necessary instead, if the intermediate directories don't exist yet.
EDIT: it's not clear from your question whether this is happening in new FileWriter() or in Desktop.open(). Please clarify.
i have tried this code. I didn't create any file. I am doing this in netbeans where server is glassfish v2
public void create_file(String file_name)
{
FileWriter file_stream;
BufferedWriter out_stream;
try
{
file_stream= new FileWriter(file_name);
this.out_stream = new BufferedWriter(file_stream);
}
catch (Exception e){//Catch exception if any
}
}
I suspect you're passing in a relative filename - and chances are the working directory isn't what you expect it to be. I suggest you use an absolute filename, or find out an appropriate directory to create the file relative to.
It would also help if you didn't swallow exceptions - if there's something going wrong, the exception is trying to tell you about it, but you're ignoring it completely.