Java creating and writing file to local directory not working - java

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

Related

How to create a json file inside the resource folder in SpringBoot?

I want to write into a json file inside the resource folder of springboot. So I wanted to check, how to create a file and insert data. If file exists after creation then add the data into file, else create file and add data.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
FileOutputStream fileOutputStream = new FileOutputStream(new
File(classLoader.getResourceAsStream("/Response.json").toString()));
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
try {
for(list){}
string result="user Should be active user";
writer.write(String.valueOf(result));
writer.close();
} catch{}
IMHO, If you're using docker or any container to deploy the apps, just let the code to write on the root folder (home where app.jar deployed), coz in the runtime actually the metadata will not accessible since it already bundled on the jar by spring-boot.

Download file showing in tomcat bin folder

When I run my war file on Tomcat server then I run my project on chrome and download the xls file from my project and this file showing in tomcat bin folder as well as download folder in our computer.
Please suggest me how we can stop this download file in tomcat bin folder
thanks
String FILE_EXTENSION = ".xlsx";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
File file = new File(filename);
// this Writes the workbook
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.flush();
out.close();
wb.dispose();
fileInputStream = new FileInputStream(file);
addActionMessage(filename + " written successfully on disk.");
i think the this problem can be sovled, just by fixing the place you want to created the file
String FILE_EXTENSION = ".xlsx";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
filename = "SearchPayment_Transactions_" + df.format(new Date()) + FILE_EXTENSION;
File file = new File(path any fixed directory like temp\filename);
As long as you specify the path where you want to generate the file then it will generating only in tht directory. PLease make proper permission is given to path to generate file, and this will solve your issue.
The file appears twice on your computer, because your servlet code saves the *.xlsx file to disk before sending it to your browser. That's the behavior your chose in your code.
Remark however, that file in your code is a relative path, so the folder you write it is the working directory (according to the OS) of your server. The value of the working directory is not defined in the Servlet Specification and may vary from system to system.
A better solution would be:
either don't write any file at all and write your data directly to ServletResponse#getOutputStream(),
or write the file to the Servlet's temporary directory, which you can obtain through (File) servletContext.getAttribute(ServletContext.TEMPDIR). E.g. you can replace your file variable with:
final File file = new File((File) servletContext.getAttribute(ServletContext.TEMPDIR), filename);

How to get path of java files including /src/

im Working on a project that can compile/run existing java files in PC.
most of code works pretty well, but im having a problem at getting the path of java files.
here are the problematic codes
void uploadJ() {
System.out.print("Insert File name : "); //ex)HelloWorld.java
FileName = sc.next();
}
void Compile(){
String s = null;
File file = new File(FileName);
String path = file.getAbsolutePath();
try {
Process oProcess = new ProcessBuilder("javac", path).start();
BufferedReader stdError = new BufferedReader(
new InputStreamReader(oProcess.getErrorStream()));
while ((s = stdError.readLine()) != null) {
FileWriter fw = new FileWriter(E_file, true);
fw.write(s);
fw.flush();
fw.close();
}
} catch...
}
For instance, when i put HelloWorld.java as a file name,
the absolute path of the HelloWorld.java should be C:\Users\user\eclipse-
workspace\TermProject\src\HelloWorld.java,
but instead, the result is C:\Users\user\eclipse-
workspace\TermProject\HelloWorld.java.
it misses /src/ so it always ends up with javac: file not found error.
When your application has been compiled, there will be no src directory. This working directory could also be set to anything.
You also can't guarantee that the file you are looking for is an actual file, in the context of a jar file, it isn't.
However, you can load files from the classpath. You can make use of Class#getResourceAsStream(String):
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.`.
Finding the file can be accomplished by calling this.getClass().getResourceAsStream("/" + FileName), with the / causing the search to occur from the resource root.
To use this with javac, you'll have to create a temporary file and populate it with the data stream you get from getResourceAsStream.

jsp how to creat a log.txt file in openshift

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.

Load file dynamically from jar

I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.

Categories