How to use this.getClass().getResource(String)? - java

I cant understand what the error of this code.
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(this.getClass().getResource(url));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}
when i try to run it, it says me "no suitable constructor found for FileInputStream(URL)". Why its happening?

Use:
getClass().getResourceAsStream(classpathRelativeFile) for classpath resources
new FileInputStream(pathtoFile) for file-system resources.

Put the file in root of folder of your class path (folder where your .class files are generated) and then use statements below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream(filePath);
Player p = new Player(inputStream );
Here filePath is the relative file path w.r.t. the root folder.

It is simpler to use getResourceAsStream
InputStream in = getClass().getResourceAsStream(url);
Player p = new Player(file);

The parameter of FileInputStream constructor is File, String ... (see http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html ), but Class.getResource return URL (see http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html), not File, or String.
Try to use
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(new File(this.getClass().getResource(url).toURI()));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}

Related

Jar executable of spring app file upload failed?

This spring app performs simple file upload,
here's the controller class
#Override
public String fileUpload(MultipartFile file) {
try{
// save uploaded image to images folder in root dir
Files.write(Paths.get("images/"+ file.getOriginalFilename()), file.getBytes());
// perform some tasks on image
return "";
} catch (IOException ioException) {
return "File upload has failed.";
} finally {
Files.delete(Paths.get("images/" + file.getOriginalFilename()));
}
}
but when i build jar and runs, it throws IOException saying,
java.nio.file.NoSuchFileException: images\8c9.jpeg.
So my question is how can i add the images folder inside the jar executable itself.
Thanks.
You should provide a full path for the images folder, or save in java.io.tmpdir creating the image folder first.
But, in my opinion you should configure your upload folder from a config file for flexibility. Take a look at this.
app:
profile-image:
upload-dir: C:\\projs\\web\\profile_image
file-types: jpg, JPG, png, PNG
width-height: 360, 360
max-size: 5242880
In your service or controller, do whatever you like, may be validate image type, size etc and process it as you like. For instance, if you want thumbnails(or avatar..).
In your controller or service class, get the directory:
#Value("${app.image-upload-dir:../images}")
private String imageUploadDir;
Finally,
public static Path uploadFileToPath(String fullFileName, String uploadDir, byte[] filecontent) throws IOException {
Path fileOut = null;
try{
Path fileAbsolutePath = Paths.get(StringUtils.join(uploadDir, File.separatorChar, fullFileName));
fileOut = Files.write(fileAbsolutePath, filecontent);
}catch (Exception e) {
throw e;
}
return fileOut; //full path of the file
}
For your question in the comment: You can use java.io.File.deleteOnExit() method, which deletes the file or directory defined by the abstract path name when the virtual machine terminates. TAKE A GOOD CARE THOUGH, it might leave some files if not handled properly.
try (ByteArrayOutputStream output = new ByteArrayOutputStream();){
URL fileUrl = new URL(url);
String tempDir = System.getProperty("java.io.tmpdir");
String path = tempDir + new Date().getTime() + ".jpg"; // note file extension
java.io.File file = new java.io.File(path);
file.deleteOnExit();
inputStream = fileUrl.openStream();
ByteStreams.copy(inputStream, output); // ByteStreams - Guava
outputStream = new FileOutputStream(file);
output.writeTo(outputStream);
outputStream.flush();
return file;
} catch (Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch(Exception e){
//skip
}
}

java.io.IOException: Stream closed accessing config files outside of jar folders

I'm executing a jar file which reads configs from a config file outside of /home/user/xxx/testFolder/jarfile, the path of config file is /opt/xxx/conf/global_config.cfg.
However, I'm able to access files inside the jar, so I assume the error is due to the file not being found.
Below is my code:
public Properties createProperties(){
Properties p = null;
ClassLoader cl = this.getClass().getClassLoader();
try (InputStream stream = cl.getResourceAsStream("/opt/xxx/conf/global_config.cfg")) {
p = new Properties();
BufferedInputStream bis = new BufferedInputStream(stream);
p.load(bis); // this is throwing the error
System.out.println(p.toString());
} catch (IOException e) {
e.printStackTrace();
}
return p;
}
What is the correct way of getting a file regardless of its path in a Linux system?
cl.getResourceAsStream("/opt/xxx/conf/global_config.cfg")
expects the resource to be available in relation to the class location. So, it will search as a relative path to the class inside the JAR. But the path /opt/xxx/conf/global_config.cfg is a absolute disk path, and for reading it , you need to use the FileInputStream
public Properties createProperties(){
Properties p = null;
ClassLoader cl = this.getClass().getClassLoader();
try (InputStream stream =new FileInputStream("/opt/xxx/conf/global_config.cfg")) {
p = new Properties();
p.load(stream);
System.out.println(p.toString());
} catch (IOException e) {
e.printStackTrace();
}
return p;
}

How to get file from resource folder as File?

I want to get a file from resources folder if it exists and create it there if it doesn't. I want to access it as file. class.getResource() doesn't work as it returns an URL. class.getResourceAsStream() gives input stream, but then I can't write in it or can I somehow?
import java.io.File;
import java.io.FileNotFoundException;
public class Statistika {
File file;
public Statistika() {
try {
file = Statistika.class.getResourceAsStream("statistics.txt");
} catch (FileNotFoundException e) {
file = new File("statistics.txt");
}
}
How to make this work?
Try using Statistika.class.getClassLoader().getResource(filename);If it returns null then you can create new file/directory. If your accessing this from jar then use Statistika.class.getClassLoader().getResourceAsStream(filename);
Hope it will solve your problem. Let me know if you found any difficulties.
Have you tried this?
File f = new File(Statistika.class.getResource("resource.name").toURI());
if (!f.isFile()){
f.getParentFile().mkdirs();
f.createNewFile();
}
Don't do file = new File("statistics.txt"); in your catch block .. just do the following
try {
File file = new File("statistics.txt");
InputStream fis = new FileInputStream(file);
fis = Statistika.class.getResourceAsStream(file.getName());
} catch (FileNotFoundException e) {
}
This is independent of whether the file exists or not.
File f = new File("statistics.txt");
try {
f.createNewFile();
} catch (IOException ex) { }
InputStream fis = new FileInputStream(f);
Use BufferedReader to insert contents to file referenced by f.

Saving file as a different name

I have a Java form in which you can select a file to open. I have that file:
File my_file = ...
I want to be able to save my file as a different name.
how can I do it using "File my_file"?
I tried:
File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);
But that doesn't save the file.
I would recommend using the Apache Commons IO library to make this task easier. With this library, you could use the handy FileUtils class that provides many helper functions for handling file IO. I think you would be interested in the copy(File file, File file) function
try{
File current_file = JPanel_VisualizationLogTab.get_File();
File newFile = new File("new_file.txt");
FileUtils.copyFile(current_file, newFile);
} catch (IOException e){
e.printStackTrace();
}
Documentation
If you want to copy it with a different name, i found this piece of Code via google
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
now you can call it with
File inF = new File("/home/user/inputFile.txt");
File outF = new File("/home/user/outputFile.txt");
copyFile(inF, outF);
it´s just important that both Files exist, otherswise it will raise an exception
You can rename the file name.
Use:
myfile.renameTo("neeFile")
There is a Method called renameTo(new File("whatever you want")); for File Objects

How to get the path of executed .jar file?

How do I get the path of a an executed .jar file, in Java?
I tried using System.getProperty("user.dir"); but this only gave me the current working directory which is wrong, I need the path to the directory, that the .jar file is located in, directly, not the "pwd".
Could you specify why you need the path?If you need to access some property from the jar file you should have a look at ClassLoader.getSystemClassLoader();
don't forget that your classes are not necessary store in a jar file.
// if your config.ini file is in the com package.
URL url = getClass().getClassLoader().getResource("com/config.ini");
System.out.println("URL=" + url);
InputStream is = getClass().getClassLoader().getResourceAsStream("com/config.ini");
try {
if (is != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
else {
System.out.println("resource not found.");
}
}
catch (IOException e) {
e.printStackTrace();
}
regards.
Taken From Java-Forumns:
public static String getPathToJarfileDir(Object classToUse) {
String url = classToUse.getClass().getResource("/" + classToUse.getClass().getName().replaceAll("\\.", "/") + ".class").toString();
url = url.substring(4).replaceFirst("/[^/]+\\.jar!.*$", "/");
try {
File dir = new File(new URL(url).toURI());
url = dir.getAbsolutePath();
} catch (MalformedURLException mue) {
url = null;
} catch (URISyntaxException ue) {
url = null;
}
return url;
}
Perhaps java.class.path property?
If you know the name of your jar file, and if it is in the class path, you can find its path there, eg. with a little regex.

Categories

Resources