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.
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 want to upload a file in static/css/question_image which is a directory in my Spring Boot project.
By using below code i am able to upload the image but it is getting stored in my local system some directory and it doesn't appear in project folder structure.
Iterator<String> itr =multipartHttpServletRequest.getFileNames();
while(itr.hasNext()){
fileName = itr.next();
MultipartFile file =multipartHttpServletRequest.getFile(fileName);
System.out.println("File name is "+file.getOriginalFilename());
byte[] byteArr = file.getBytes();
File convFile = new File("static/"+file.getOriginalFilename());
convFile.createNewFile();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(convFile);
stream.write(byteArr);
stream.close();
I'm guessing your file is in the "static" sub-directory of the current directory, which, possibly, is the directory containing your JAR. You can't write back into the "project folder structure", as that appears to be in the JAR.
I suggest you rethink what you are intending to do with the output and where it needs to go.
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.
I have created a java project in which I am using a properties file also which is created inside a java packgae named abcedf
so package name is abcdef which consists a class name abc.java and a property file named drg.properties ,now from class abc.java i am referring to that properties file as..
abc tt = new abc();
URL url = tt.getClass().getResource("./drg.properties");
File file = new File(url.getPath());
FileInputStream fileInput = new FileInputStream(file);
now this file is referred and my program runs successfully but when I am trying to make it executable jar then this property file is not referred
please advise what is went wrong while creating the property file.
Use
tt.getClass().getResourceAsStream("./drg.properties");
to access the property file inside a JAR. You will get an InputStream as returned object.
-------------------------------------------------
Here is an example to load the InputStream to Properties object
InputStream in = tt.getClass().getResourceAsStream("./drg.properties");
Properties properties = new Properties();
properties.load(in); // Loads content into properties object
in.close();
If your case, you can directly use, the InputStream instead of using FileInputStream
When you access "jarred" resource you can't access it directly as you access a resource on your HDD with new File() (because resource doesn't live uncompressed on your drive) but you have to access resource (stored in your application jar) using Class.getResourceAsStream()
Code will looks like (with java7 try-with-resource feature)
Properties p = new Properties();
try(InputStream is = tt.getClass().getResourceAsStream("./drg.properties")) {
p.load(is); // Loads content into p object
}
When you save an object in java (using serialize), where is the file created?
For example if you used this method http://www.rgagnon.com/javadetails/java-0075.html
If you are using the ObjectOutputStream for serialization and wrapping it around a FileOutputStream then the objects will go into that file.
For example (from the ObjectOutputStream Javadoc):
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(12345);
oos.writeObject("Today");
oos.writeObject(new Date());
oos.close();
This will create a file "t.tmp" in the working directory of the java application.
And about the working directory...
If you are using an IDE to launch your application then the working directory depends on where the IDE puts the compiled classes and how it runs your application.
You can use the following code to print the working directory:
File f = new File(".");
System.out.println(f.getAbsolutePath());
The "." represents the "current" directory.
Generally wherever you saved it to. How is the File created?
Update
From the link, it seems the code is creating a File by instantiating the file from aString representing the name, with no path. Others have addressed that.
Instead, I would like to stress the following. Do not create files there. If they are temporary files, put them in the temp directory, as already mentioned in another answer. If they are files the program might need to access later, put them in a stable & reproducible path, e.g. a sub-directory of user.home.
E.G. (pseudo-code, untested)
String name = "data.ser";
String[] pkgs = {"com", "our", "main"};
File f = new File(System.getProperty("user.home");
for (String pkg : pkgs) {
f = new File(f, pkg);
}
f = new File(f, name);
...
If you mean the standard serialization using java.io.Serializable, then there is no "standard" location. Your rather create an instance of ObjectOutputStream that decorates an aribtrary OutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(someObject);
oos.close();
In this example, the object was written in-memory. If you use a FileOutputStream, then you could serialize your object to an arbitrary file.
Edit:
In your link, the resulting file will be stored in the "current working directory" which is the directory from where you executed your Java app using the java ... command.