How to get files from a project folder - java

The folder is /src/img. I need to get all file names(png files) from img folder and all subfolders.I dont know the full path to the folder so i need only to focus the project resourse. I need them in array. Using Java8 and Eclipse Mars.
So far this works:
try {
Files.walk(Paths.get("/home/fixxxer/NetBeansProjects/Installer/src/img/")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
} catch (IOException ex) {
Logger.getLogger(InstallFrame.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that the folder need to be called like this:
/img cause it is inside the project
Thanks in advance :)

You can use relative paths.
Here, I am assuming that Installer is your project name. Otherwise, you can edit the relative path according to your project setup.
Files.walk(Paths.get(".//src//img//")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});

If you place your file
test.png
under
/src/resources/org/example
you can access it from your class
org.example.InstallFrame
using
final URL resource = InstallFrame.class.getResource("test.png");
respectively
final InputStream resourceAsStream = InstallFrame.class.getResourceAsStream("test.png");

First find the base path and then use in your code
String basePath = ClassLoader.getSystemResource("").getPath();
//move basepath to the path where img directory
//present in your project using ".."
//like basepath = basepath+"..\\..\\img"+
Files.walk(Paths.get(testPath)).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});

Related

java.nio.file.AccessDeniedException error?

Im trying to zip my created folder. Right now im testing localy and it create folder but after that i want to zip it.
This is my code for zip:
public static void pack(final String sourceDirPath, final String zipFilePath) throws IOException {
Path p = Files.createFile(Paths.get(zipFilePath));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
Path pp = Paths.get(sourceDirPath);
Files.walk(pp).filter(path -> !Files.isDirectory(path)).forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
} }
But im getting an error AccessDeniedException. Is there any option to zip created folder, i dont want to zip file because in that folder i will have subfolders, so i want to zip main folder. Any suggestion how can i achive that?
According to:
Getting "java.nio.file.AccessDeniedException" when trying to write to a folder
I think you should add the filename and the extension to your 'zipFilePath', for example: "C:\Users\XXXXX\Desktop\zippedFile.zip"

Upload file to Spring Boot Resource Folder, should not be that hard right

I checked all over the internet and still cannot find the correct answer. I want to upload a file to the resources folder from Spring. So I can get the file from the heroku server when I deploy it.
For example applicationname/herokuapp.com/image.jpg
The structure of my app:
I tried and got a few problems :
File not found exception
Illegal char <:> at index 2
The file path I get is in the target folder??
Can't find path
I just need to get the correct path to the resources folder but I can't get it.
My controller with the following method looks like this:
#PostMapping(value = "/sheetmusic")
public SheetMusic create(HttpServletRequest request, #RequestParam("file") MultipartFile file, #RequestParam("title") String title, #RequestParam("componist") String componist, #RequestParam("key") String key, #RequestParam("instrument") String instrument) throws IOException {
URL s = ResourceUtils.getURL("classpath:static/");
String path = s.getPath();
fileService.uploadFile(file,path);
SheetMusic sheetMusic = new SheetMusic(title,componist,key,instrument,file.getOriginalFilename());
return sheetMusicRepository.save(sheetMusic);
}
The FileService:
public void uploadFile(MultipartFile file, String uploadDir) {
try {
Path copyLocation = Paths
.get(uploadDir + File.separator + StringUtils.cleanPath(file.getOriginalFilename()));
Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
}
I read something about jar but I don't understand it. I did not think it was this hard to just upload a file to a folder but I hope you guys can help me out!
EDIT :
When I add this :
String filePath = ResourceUtils.getFile("classpath:static").toString();
It will upload to the target folder which is not right.
EDIT 2 : IT IS FIXED
This is the right way to get the correct path :
String path = new File(".").getCanonicalPath() + "/src/main/webapp/WEB-INF/images/";
fileService.uploadFile(file,path);
My folder structure is the following:
main
-java
- webapp
- WEB-INF
- images
Then I had to put this code into my MainApplicationClass
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Register resource handler for images
// Register resource handler for images
registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/images/")
.setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
}
What you are trying to do here (replacing a file/uploading a file INTO a package .jar file) does not work, it is literally impossible.
You need to upload your file somewhere else, be that S3, some network drive etc, so that you application can reference it.

How can I add a custom file(built for every created project) in Eclipse?

I want to create a plug-in for Eclipse in which every custom project I create has a specific template and specific files. I managed to create the template(folder1/folder_name1, folder1/folder_name2, folder2/folder_name1, etc), but I am still trying to figure it out on how to make sure that when I create this type of project, some custom files are created(namely in folder_name1 and folder_name2). How would you think is the best way to do it?
I have tried using IFile, but I'm not really sure on how to use it.
This is the function that creates a project:
public static IProject createProject(String projectName, URI location) {
Assert.isNotNull(projectName);
Assert.isTrue(projectName.trim().length() > 0);
IProject project = createBaseProject(projectName, location);
try {
addNature(project);
String[] paths = {
"folder1/folder_name1", //$NON-NLS-1$
"folder1/folder_name2",
"folder2/folder_name1",
"folder2/folder_name2"}; //$NON-NLS-1$
addToProjectStructure(project, paths);
} catch (CoreException e) {
e.printStackTrace();
project = null;
}
return project;
}
I expect that a file(let's name it test.cpp) it's created in folder_name1 and folder_name2 for each folder1/2.
You have project object ie IProject project = createBaseProject(projectName, location);
you can use the following code snippet
.... other code ...
IFile templateFile = project.getFile("/projectPath/folder1/folder_name1/templateFile1.txt");
String fileContents = "Template File Contents";//You can get the contents from source
InputStream source = new ByteArrayInputStream(contents.getBytes());
templateFile .create(source, false, null);
I hope in this you can create file specific to project folder. You can also get answers from others.

How to get the root path of my project?

I have JSP projects that run in Tomcat developed in Eclipse.
I want to have some files which I store inside the project.
Here is the project structure that I have:
.settings
build
data
ImportedClasses
src
WebContent
.classpath
.project
I want to access the data folder from my code in JSP file which located in WebContent.
Tried some code below:
File userDataDirFile = new File ( "data" );
String path = userDataDirFile.getAbsolutePath();
prints
C:\Program Files\eclipse\data\users
Then
this.getClass().getClassLoader().getResource("").getPath()
prints
C:/Workspaces/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/survey/WEB-INF/classes/
Another one:
System.getProperty("user.dir")
prints
C:\Program Files\eclipse
There is no code that I tried (I think the 2nd solution supposed to work, but it doesn't) can locate me to root folder of my project. Anyone can advise?
String caminhoProjeto = Thread.currentThread().getContextClassLoader().getResource("").getPath();
This is like "src" path, but is the "classes" path of binaries files context after deployment and runtime.
My class for example of the necessarie use of this way "root dir of project":
PropertiesReader.java:
public class PropertiesReader {
public static String projectPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
public static String propertiesPath = "/META-INF/";
public static Properties loadProperties(String propertiesFileName) throws IOException {
Properties p = new Properties();
p.load(new FileInputStream(projectPath + propertiesPath + propertiesFileName));
return p;
}
public static String getText(String propertiesFileName, String propertie) {
try {
return loadProperties(propertiesFileName).getProperty(propertie);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return propertie;
}
}
PersonRegistration.java:
#ManagedBean
public class PersonRegistration {
private Integer majority = Integer.parseInt(PropertiesLeitor.getText("Brasil.properties", "pessoa.maioridade"));
}
Brasil.properties (within src / META-INF):
pessoa.maioridade = 18
Edit : File that are not in WebContent will not be deployed with your war. you have to put files used in you code inside the WebContent and try with ServletContext which point to the root folder of the your web application :
if your file is at the same folder as WEB-INF then :
ServletContext context = getContext();
String fullPath = context.getRealPath("/data");
by the way if you don't want to give direct access to data file it's recommanded to put it in WEB-INF so that no one can have access to them directly.

java: Open folder on button click

In java, how can we open a separate folder (e.g. c:) for user on click of a button, e.g like the way " locate this file on disk" or "open containing folder" does when we download a file and we want to know where it was saved. The goal is to save user's time to open a browser and locate the file on disk.
Thanks ( image below is an example from what firefox does)
I got the answer:
Here is what worked for me in Windows 7:
File foler = new File("C:\\"); // path to the directory to be opened
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
try {
desktop.open(foler);
} catch (IOException e) {
}
Thanks to #AlexS
I assume you have a file. With java.awt.Desktop you can use something like this:
public static void openContaiingFolder(File file) {
String absoluteFilePath = file.getAbsolutePath();
File folder = new File(absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf(File.separator)));
openFolder(folder);
}
public static void openFolder(File folder) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(folder);
}
}
Be awrae that if you call this with a File that is no directory at least Windows will try to open the file with the default program for the filetype.
But I don't know on which platforms this is supported.

Categories

Resources