Upload an Image using springboot in linux - java

I try to upload an image using spring-boot. The app should be capable for Linux and windows. The below codes are working only in windows, not in Linux. I tried in different ways. getDefaultFolderPath() is creating folder in both OS if not exists. But Files.write(path, bytes); is working only in windows.
String imageWindowsPath = "C:\\myapp\\";
String imageLinuxPath = "user.home";
private String uploadImage(MultipartFile file, HttpServletRequest request) {
String fileName = "blur.png";
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
Path path = Paths.get(getDefaultFolderPath() + fileName);
Files.write(path, bytes);
}
//few other codes
retrun "";
}
//Creating folder if not exists... This is working for both OS
public String getDefaultFolderPath() {
String path = "";
try {
String os = System.getProperty("os.name");
if (os.toUpperCase().indexOf("WINDOWS") != -1) {
File file = new File(imageWindowsPath+"slider");
if (!file.exists())
file.mkdirs();
path = imageWindowsPath+"/slider/";
}
else if (os.toUpperCase().indexOf("LINUX") != -1) {
String userHome = System.getProperty(imageLinuxPath);
String appName = "slider";
Path linuxpath = Paths.get(userHome, appName);
Files.createDirectories(linuxpath);
path = imageLinuxPath+"/slider/";
}
} catch (Exception e) {
e.printStackTrace();
}
//few codes
return path;
}
Please suggest me a solution if anyone knows. Thanks in advance.

String imageLinuxPath = "user.home";
String userHome = System.getProperty(imageLinuxPath);
String appName = "slider";
Path linuxpath = Paths.get(userHome, appName);
Files.createDirectories(linuxpath);
creates a directory based on the environment variable "user.home"
path = imageLinuxPath+"slider/";
return path;
returns "user.homeslider/"
Since the content of the environment variable user.home is probably not "user.home", the path will not be the directory that was created.
This means that you are trying to write to a directory that does not exist.
I would like to add that the difference between Windows and Linux is entirely your own creation. Java can treat them exactly the same way if you have a Windows property with the home path.

Related

Java - WildcardFileFilter: Works on Mac, doesn't work on CentOs

WildcardFileFilter works on Mac locally, doesn't work on CentOS.
Same exact code
File definitely exists in given folder:
/path/file_170301.ZIP
Appreciate any help.
protected String getFileName() {
String fileMask = MonthlyFileName(getProcessDate())
.replaceAll("[0-9]{2}\\.ZIP", "*.ZIP");
File dir = new File(context.getWorkdir() + "/");
FileFilter fileFilter = new WildcardFileFilter(fileMask);
String fileName = (dir.listFiles(fileFilter).length == 1)
? dir.listFiles(fileFilter)[0].getName() : fileMask;
return fileName;
}
can't open `/path/file_1703*.ZIP': No such file or directory

Java - FileNotFoundException: /mnt/sdcard: open failed: EISDIR (Is a directory)

I'm trying to decompress RAR archive on my Android device from the sd card but I got an error:
java.io.FileNotFoundException: /mnt/sdcard: open failed: EISDIR (Is a directory)
I chose a rar-file and try to decompress it in my sd-card.
Error says that it's not directory but it is. I have no idea how I can fix it.
My code:
public static void unrar(File srcRarFile, String destPath, String password) throws IOException {
if (null == srcRarFile || !srcRarFile.exists()) {
throw new IOException(".");
}
if (!destPath.endsWith(SEPARATOR)) {
destPath += SEPARATOR;
}
Archive archive = null;
OutputStream unOut = null;
try {
archive = new Archive(srcRarFile, password, false);
FileHeader fileHeader = archive.nextFileHeader();
while(null != fileHeader) {
if (!fileHeader.isDirectory())
{
// 1 destDirName destFileName
String destFileName = "";
String destDirName = "";
destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("/", "\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
// 2
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
//
// ERROR:
unOut = new FileOutputStream(dir);
archive.extractFile(fileHeader, unOut);
unOut.flush();
unOut.close();
}
fileHeader = archive.nextFileHeader();
}
archive.close();
} catch (RarException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(unOut);
}
}
Clear thing. You first create the directory /mnt/sdcard (variable dir is equal to destDirName in your code) and then you try to create a file with the same same. This will not work. Use a name like /mnt/sdcard/abc.rar and it might work. Here is how you create the corresponding File object:
File file = new File(dir, "abc.rar");
Btw: creating a directory called /mnt/sdcard will probably not work due to a lack of permissions. If it's an SD card, Android will do this job for you anyway. If it isn't an SD card, its not a good idea to create a directory with this name.
PS2: After further reviewing your code I see things which are not good style:
You are using the separater variable and indexOf/substring to find the parent directory.
You replace "/" (the android path separator) by "\" which is only used in Windows
You swap between File and string
You can simply get rid of all this by using File.getParent()/File.getParentFile()
Check if you have set permissions in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Retrieve the web app root path in JSF Managed Bean

Im trying to access the example/web folder (see below in the image) in a jsf managed bean but cant seem to find a way to do it
thx
Try
FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath()
for build relative url's to resources in your app.
If you want the real path...
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String realPath = ctx.getRealPath("/");
If you want to get it as a File for some reason, then you need ExternalContext#getRealPath(). This converts a relative web path to an absolute disk file system. Since you need the web's root folder, just pass in /:
String absoluteWebPath = externalContext.getRealPath("/");
File webRoot = new File(absoluteWebPath);
// ...
Unrelated to the concrete problem, whatever functional requirement you've had in mind for which you thought that having an absolute local disk file system path to the web folder is the right solution, it has most definitely to be solved differently. And indeed, as per your comment on the other answer,
because Im trying to upload some file inside the folder and using the relative path
you're going the wrong path. You should not store uploaded files in there if you intend to keep them longer than the webapp's deployment lifetime. Whenever you redeploy the webapp (and on some server configs even when you restart the server), the uploaded files would get completely lost, simply because they are not contained as part of the original WAR file. Even more, some heavy server configs don't expand the WAR on disk at all, but in memory instead, the getRealPath() would then always return null.
Rather store it in a fixed disk file system path outside the server's deploy folder. Add that path in turn as a new server context or docroot, so that it's accessible on a different (virtual) context path. Or homegrow a servlet which gets an InputStream of it from disk and writes it to OutputStream of the response. See also this related answer: Uploaded image only available after refreshing the page
Try:
String relativePath="/resources/temp/";
String absolutePath= FacesContext.getCurrentInstance.getExternalContext().getRealPath(relativePath);
File file = new File(absolutePath);
to get real path.
Create a tmp file in resources/temp/ to avoid any exception.
Just wanted to thank Balus C. Code Java with JSP, in Tomcat/Tomee server I the following code that works:
private Boolean SaveUserItemImage(Part ui, String bid) throws IOException {
Boolean fileCreate = false;
OutputStream out = null;
InputStream filecontent = null;
ExternalContext ctx = context().getExternalContext();
String absoluteWebPath = ctx.getRealPath("/");
String resource_path = absoluteWebPath + "\\resources\\";
String image_path = resource_path + "\\" + this.itemType + "_images\\";
String buildFileName = image_path + bid + "_" + getFileName(ui);
File files = null;
try {
files = new File(buildFileName);
fileCreate = true;
} catch (Exception ex) {
System.out.println("Error in Creating New File");
Logger.getLogger(ItemBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (fileCreate == true) {
if (files.exists()) {
/// User may be using same image file name but has been editted
files.delete();
}
try {
out = new FileOutputStream(files);
filecontent = ui.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
fileCreate = true;
} catch (FileNotFoundException fne) {
fileCreate = false;
Logger.getLogger(ItemBean.class.getName()).log(Level.SEVERE, "SaveUserItemImage", fne);
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
files = null;
}
}
return fileCreate;
}

file path from \ to /

I have this problem: I am choosing a file from JFileChooser and if i take a system print i get this path: C:\Users\Joakim\Desktop\dude.txt and when i want to use this link to copy this file to another location i need to have the path like this: C://Users/Joakim/Desktop/dude.txt
How can i do this?
public void upload(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser(getProperty + "/desktop/");
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
System.out.println(fileName); //name of the file
File selectedFile = chooser.getSelectedFile();
System.out.println(selectedFile); //path of the file
//File path= selectedFile.replaceAll('/','/');
String serverDirectory = ("C://Users/Joakim/Dropbox/Project RMI/SERVER/");
byte[] filedata = cf.downloadFile(selectedFile);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(serverDirectory + fileName));
output.write(filedata, 0, filedata.length);
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
Thanks in Advance :)
Edit: So this did not work out as i planed. I wanted to change the path to C://Users/Joakim/Desktop/dude.txt but thats not enough. I need to have //C://Users/Joakim/Desktop/dude.txt. The problem i have now is to get that and still use it as a File. I did test out
File newFil = new File("//" + selectedFile);
byte[] filedata = cf.downloadFile(nyFil);
This do not work for me. I still get out C://Users/Joakim/Desktop/dude.txt
Do someone have a tip or two? :)
You should really be using the system properties file.separator:
Character that separates components of a file path. This is "/" on
UNIX and "\" on Windows.
String fileSeparator = System.getProperty("file.separator");
You can also access the file separator as File.separator
Consider breaking up your path to incorporate the use of this property in lieu of forward or backward slashes.
It's simple, try this :
String first = "C:\\Mine\\Java";
String second = first.replace("\\", "/");
second = second.replaceFirst("/", "//");
System.out.println(second);
OUTPUT :
Hope this might help in some way.
Regards
This should work: C:\Users use double \
Try with this
/**
* Prepare dropbox path from the path.
*
* #param path
* that is to be formated.
* #return
* Return dropbox formated path.
*/
public static String createDropboxPathFormat(String path) {
// Replaced all \ with / of the path.
String dropboxPath = path.replaceAll("[\\\\]", "/");
// Finally replaced all // with /
dropboxPath = dropboxPath.replaceAll("[//]", "/");
return dropboxPath;
}

How to Declare Folder Path?

I have a desktop application using Swing library. Application is running a batch file. So I created a lib folder in main project directory and put batch file in it. To run this, I am showing lib\a.exe to run this. It is working on my laptop. I exported .jar and put lib folder next to it. It is working on my laptop, but not working on some other laptops. How to fix this?
Error message is: Windows cannot found lib\a.exe.
String command = "cmd /c start lib\\a.exe";
try {
Runtime.getRuntime().exec(command);
increaseProgressBarValue();
} catch (IOException e) {
e.printStackTrace();
}
You need two things:
find the directory of the jar file of your application
call a.exe with the correct working directory
You can get the location of the jar with the getJar method below:
private static File getJar(Class clazz) throws MalformedURLException {
String name = clazz.getName().replace('.','/') + ".class";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL url = cl.getResource(name);
System.out.println(url);
if (!"jar".equals(url.getProtocol())) {
throw new MalformedURLException("Expected a jar: URL " + url);
}
String file = url.getPath();
int pos = file.lastIndexOf('!');
if (pos < 0) {
throw new MalformedURLException("Expected ! " + file);
}
url = new URL(file.substring(0, pos));
if (!"file".equals(url.getProtocol())) {
throw new MalformedURLException("Expected a file: URL " + url);
}
String path = url.getPath();
if (path.matches("/[A-Za-z]:/")) { // Windoze drive letter
path = path.substring(1);
}
return new File(path);
}
To call lib\a.exe, you can do something like this:
File jar = getJar(MyClass.class); // MyClass can be any class in you jar file
File dir = jar.getParentFile();
ProcessBuilder builder = new ProcessBuilder();
builder.command("lib\\a.exe");
builder.directory(dir);
...
Process p = builder.start();
...
Maybe you have to try if this folder lib exists and if it doesn't than create it with
file.mkdir();
This is a just a checking. But your filepath must be like this ../lib/a.exe.

Categories