Jackson writeValue() to file not working with relative path - java

I'm trying to write an object to json file by jackson.
If i provide an absolute path "D:/Projects/quiz-red/src/main/resources/com/models/Quizzes.json" it's working and file appears in the directory
But if i provide a relative path - "/com/models/Quizzes.json" i'm just getting Process finished with exit code 0 in console and nothing happens. What am I doing wrong?
There is my code:
public static void writeEntityToJson(Object jsonDataObject, String path) throws IOException {
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(new File(path), jsonDataObject);
}
public static void main(String[] args) throws IOException {
Quiz quiz = new Quiz(5L, "Title", "Short desc");
writeEntityToJson(quiz, "/com/models/Quizzes2.json");
}
I want to save a file to resources from DataProvider using relative path
Exception:
Exception in thread "main" java.io.FileNotFoundException: com\models\Quizzes5.json (The system cannot find the path specified)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:237)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
at com.fasterxml.jackson.core.JsonFactory.createGenerator(JsonFactory.java:1223)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:942)
at com.utils.DataProvider.writeEntityToJson(DataProvider.java:33)
at com.utils.DataProvider.main(DataProvider.java:50)

Related

Cannot read resource from jar

I have the following prefix:
String prefix = TemplatesReader.class.getClassLoader().getResource("templates/").getPath();
and have method
public byte[] read(String pathToTemplate) {
return Files.readAllBytes(Paths.get(prefix + pathToTemplate));
}
in intellij idea works correctly, but when starting jar an error occurs:
java.nio.file.NoSuchFileException: file:/app.jar!/BOOT-INF/classes!/templates/request-orders/unmarked/RequestOrderUnmarked.pdf
You must not assume that a resource is a file. When the resource is inside a .jar file, it is a part of that .jar file; it is no longer a separate file at all.
You cannot use Files or Paths to read the resource.
You cannot use the getPath() method of URL. It does not return a file name. It only returns the path portion of the URL (that is, everything between the URL’s scheme/authority and its query portion), which is not a file path at all.
Instead, read the resource using getResourceAsStream:
private static final String RESOURCE_PREFIX = "/templates/";
public byte[] read(String pathToTemplate)
throws IOException {
try (InputStream stream = TemplatesReader.class.getResource(
RESOURCE_PREFIX + pathToTemplate)) {
return stream.readAllBytes();
}
}

.xls file not detected java

When I try to load the xls file it doesn't work even though is in the same folder. I also tried it with absolute paths.
(It all happened because of missing jars, here is the list with all of them. To solve the issue of relative paths the url.getResource() from below works fine.)
My Jar List(Image)
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream f = new FileInputStream("MP.xls");
HSSFWorkbook l = new HSSFWorkbook(f);
}
}
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream f = new FileInputStream("C:\\Users\\alumno.Alumno-PC\\Documents\\NetBeansProjects\\pruebas xlsx\\src\\pruebasxlsx\\MP.xls");
HSSFWorkbook l = new HSSFWorkbook(f);
}
}
This is where the file is located(picture)
This is the error with relative path:
Exception in thread "main" java.io.FileNotFoundException: MP.xls (El sistema no puede encontrar el archivo especificado)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:111)
at pruebasxlsx.Main.main(Main.java:22)
this is the error with an absolute path
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/math3/util/ArithmeticUtils
at org.apache.poi.poifs.property.RootProperty.setSize(RootProperty.java:59)
at org.apache.poi.poifs.property.DirectoryProperty.<init>(DirectoryProperty.java:52)
at org.apache.poi.poifs.property.RootProperty.<init>(RootProperty.java:31)
at org.apache.poi.poifs.property.PropertyTable.<init>(PropertyTable.java:58)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:99)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:272)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:399)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:381)
at pruebasxlsx.Main.main(Main.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.math3.util.ArithmeticUtils
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
... 9 more
The FileInputStream with the absolute path works. Just the reading with HSSFWorkbook- misses a library.
The relative path is a volatile option. If the file is a read-only source, bundle it with the application, and do not use a File (file system file), but use a resource, a "file" on the class path, possibly bundled in an application jar.
InputStream f = Main.class.getResourceAsStream("/pruebasxslx/MP.xls");
HSSFWorkbook l = new HSSFWorkbook(f);
For HSSFWorkbook a library with org.apache.commons.math3 classes is not found,
an indirect needed library.
As these library dependencies are extra work, already done by others, and involving moving coherent versions of all libraries to work together, one should better use for instance maven, a build infrastructure. Maven (or gradle) projects are supported by most IDEs, and have a bit different directory structure.
File input stream gets the file named by the path name in the file system - that means an absolute path, as parameter, not relative path.
If you want to load a file from the location of your class use:
URL url = class.getResource("file.txt");
and then get absolute path of it by using:
url.getPath();
So, below solution should work (it can be polished but you will get an idea):
public class Main {
static URL url = Main.class.getResource("MP.xls");
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream f = new FileInputStream(url.getPath());
HSSFWorkbook l = new HSSFWorkbook(f);
}
}

how to save created file to path specified in application.properties file in spring boot

I have a method which creates new file after every execution I don't want to hardcode file path in code so I added a new property in application.properties file like
jmeter.jmx.path=D:\\PerformanceTesting\\JMXFiles\\
and instance variable which holds value like
#Value("${jmeter.jmx.path}")
private String jmxPath;
want to get the value of a variable inside method
public void saveAsJmxFile(HashTree projectTree, String fileName) throws IOException {
//TODO
SaveService.saveTree(projectTree, new FileOutputStream(jmxPath+fileName+".jmx"));
}
its not woking for me, but if i hardcode then it i'll work.
public void saveAsJmxFile(HashTree projectTree, String fileName) throws IOException {
//TODO remove hardcoded jmxPath
SaveService.saveTree(projectTree, new
FileOutputStream("D:\\PerformanceTesting\\JMXFiles\\"+fileName+".jmx"));
}
just make sure that the directory is exist
Files.createDirectories(Paths.get(jmxPath));
i'm using java8+ nio here

what is the correct file path in eclipse spring

I am working on an introduction to spring course, but I have an issue with my SpringConfig.xml file path. As show on the picture, I just added it everywhere as a hailmary but that's not working either:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [SpringConfig]; nested exception is java.io.FileNotFoundException: class path resource [SpringConfig] cannot be opened because it does not exist
My path:
Main method code:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig");
}
please don't forget to add the file extension ".xml", spring will read it from src/main/resource
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml");
}

sub directory and main directory monitoring in java [duplicate]

This question already has answers here:
Monitor subfolders with a Java watch service
(3 answers)
Closed 6 years ago.
My program is monitoring any file change in specified file path, if there's any new file coming, it will raise a notification, But going to fail when there's any sub folder created in parent folder. The file path for parent folder is being monitor C:/play but when there is a new sub folder created like C:/play/abcinside the parent folder, my program able to detect, but when i am trying to insert any file into abc folder, my program is not able to detect that new file has been created. I have tested various methods but unfortunately i can't let it work.Anyone able to provide me any guide on my reference link?My sample code is following the guide in my reference link
This is my source code after adding into the function for checking sub directory
public class fileStatus
{
public static void main(String [] args) throws InterruptedException
{
try(WatchService svc = FileSystems.getDefault().newWatchService())
{
Map<WatchKey, Path> keyMap = new HashMap<>();
Path path = Paths.get("C:/play");
fileStatus fd = new fileStatus();
fd.registerAll(path);
keyMap.put(path.register(svc,
StandardWatchEventKinds.ENTRY_CREATE),
path);
WatchKey wk ;
do
{
wk = svc.take();
Path dir = keyMap.get(wk);
for(WatchEvent<?> event : wk.pollEvents())
{
WatchEvent.Kind<?> type = event.kind();
Path fileName = (Path)event.context();
System.out.println("\nThe new file :"+fileName+ "Event :" +type); //print the new file name
}
}while(wk.reset());
}
catch(IOException e)
{
System.out.println("Problem io in somewhere");
}
}
private void registerAll(Path path) throws IOException
{
Files.walkFileTree(path, new SimpleFileVisitor<Path>()
{
#SuppressWarnings("unused")
public FileVisitResult preVisitDireotry(Path path,BasicFileAttributes attrs) throws IOException
{
return FileVisitResult.CONTINUE;
}
});
}
}
This is my reference code and my folder structure look like this,
/root
/Folder A
/test.txt
/Folder B
/abc.txt
In short, you have only registered the parent directory to be watched. Any sub-directories you create will not be watched. See here.

Categories

Resources