I've got a problem with my classpath within a jar file. With pictures
getClass().getResource("picture.png") works fine. But I need to get a mp3 file.
If I put in the whole path outside of the jar file it works just fine, however if i try it without the full path like getClass().getResource("picture.png") it says "File not Found".
So I'm looking for a solution for the path of song.mp3 so that if I build the .jar and open it on a different computer the song still plays.
this is my code:
package bgmusic;
import java.io.*;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class Bgmusic {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try{
Player player = Manager.createPlayer(new MediaLocator(new File("song.mp3").toURI().toURL()));
player.start();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
If the file is inside of your jar, you can not use new File("song.mp3");. The file expects it to be inside of your normal os path, which it's not.
To get files from within your jar you need to use getResource
Example, assuming song.mp3 is in the root of your jar file and not in a directory:
URL url = this.getClass().getResource("song.mp3");
From within a static method you should be able to get it as follows
URL url = BgMusic.class.getResource("song.mp3");
Related
I'm trying to pass a file from the main method to another class that should handle it, but while the file is recognized in the main class, it throws this error in the second one.
Exception in thread "main" java.io.FileNotFoundException: file:/home/giovanni/Desktop/spring-course/exercises-part2/word-inspection/target/classes/words.txt (File o directory non esistente)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.util.Scanner.<init>(Scanner.java:639)
at com.vanny96.WordInspection.<init>(WordInspection.java:16)
at com.vanny96.App.main(App.java:13)
The path for the file is correct, and the file is there, so I have no idea why it isn't working.
I tried looking around for a solution but couldn't find any, and the fact that the file works fine in the main method while not in another one confused me a lot, if you could point me to a thread where this is solved it would be enough!
Here is the code:
Main App
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
public class App {
public static void main(String[] args) throws FileNotFoundException
{
URL fileUrl = App.class.getClassLoader().getResource("words.txt");
File file = new File(fileUrl.toString());
WordInspection inspector = new WordInspection(file);
}
}
WordInspection class
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordInspection {
private File file;
private Scanner reader;
public WordInspection(File file) throws FileNotFoundException {
this.file = file;
this.reader = new Scanner(this.file);
}
}
I think the Scanner is not able to resolve the file as an URL, but is able to resolve it as an URI.
If you change the line:
File file = new File(fileUrl.toString());
to
File file = new File(fileUrl.toURI());
your Scanner should be able to resolve the file (i have tested it). You will have to add an additional throws class for the toUri() method.
I have an image in a directory.
I want to make a copy of that image with a different name without doing harm to the original image in the same directory.
So there will be two same images in one folder with a different name.
I want a basic code like I tried -
File source = new File("resources/"+getImage(0));
File dest = new File("resources/");
source.renameTo("resources/"+getImage(0)+);
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
When I upload the same image to the Amazon server multiple times in automation and then it starts giving issue to upload.
So we want to upload a mirror copy of image everytime.
In eclipse generally have resources folder. I want to make copy of a original image every-time before we upload and delete it after upload.
Kindly suggest some approach
You can just copy the file and use StandardCopyOption.COPY_ATTRIBUTES
public static final StandardCopyOption COPY_ATTRIBUTES
Copy attributes to the new file.
Files.copy(Paths.get(//path//to//file//and//filename),
Paths.get(//path//to//file//and//newfilename), StandardCopyOption.COPY_ATTRIBUTES);
Not a perfect solution, but Instead of handling pop-up box we can directly force file path into the form: [I have used date-stamp for creating new filenames but some different logic could also be used viz- Random String appender etc.]
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Upload {
private static final String SRC_RESOURCES_FILE_PATH = System.getProperty("user.dir")+"/src/resources/";
File s1 = new File(SRC_RESOURCES_FILE_PATH+"Img1.png");
File s2 = new File(SRC_RESOURCES_FILE_PATH+"Img"+getDateStamp()+".png");
#Test
public void uploadFunction() throws IOException {
copyFileUsingJava7Files(s1,s2);
}
private String getDateStamp(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date).toString();
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}
I have a requirement where I have to create 1 xml file inside my .zip folder.
Can you please let me know how can I achieve this using java/scala?
Also let me know can I directly update .zip folder Array[Byte] and add extra Array[Byte] for my new xml file ?
If you are using Java 7 and later, then you should use Zip File System
The following code sample shows how to create a zip file system and
copy a file to the new zip file system.
import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
This post could help you: Appending files to a zip file with Java
It is possible to update individual files in a JAR file using the jar command as follows:
jar uf TicTacToe.jar images/new.gif
Is there a way to do this programmatically?
I have to rewrite the entire jar file if I use JarOutputStream, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the jar tool, I had expected there to be a similar way to do it programmatically.
It is possible to update just parts of the JAR file using Zip File System Provider available in Java 7:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
Yes, if you use this opensource library you can modify it in this way as well.
https://truevfs.java.net
public static void main(String args[]) throws IOException{
File entry = new TFile("c:/tru6413/server/lib/nxps.jar/dir/second.txt");
Writer writer = new TFileWriter(entry);
try {
writer.write(" this is writing into a file inside an archive");
} finally {
writer.close();
}
}
I made a desktop app in java with netbeans platform. In my app I want to give separate copy-paste and cut-paste option of file or folder.
So how can I do that? I tried Files.copy(new File("D:\\Pndat").toPath(),new File("D:\\212").toPath(), REPLACE_EXISTING);. But I don't get the exact output.
If there any other option then suggest me.
In case of "cut-paste" you can use renameTo() like this:
File source = new File("////////Source path");
File destination = new File("//////////destination path");
if (!destination.exists()) {
source.renameTo(destination);
}
In case of "copy-paste" you need to read in Input and Output stream.
Use FileUtils from apache io and do FileUtils.copyDirectory(sourceDir, destDir);
You can also do the following file operations
writing to a file
reading from a file
make a directory including parent directories
copying files and directories
deleting files and directories
converting to and from a URL
listing files and directories by filter and extension
comparing file content
file last changed date
Download link for apache i/o jar.
I think this question relates to using the system clipboard for copying a file specified in a Java app and using the OS "Paste" function to copy the file to a folder. Here is a short instructional example that will show you how to add a single file to the OS clipboard for later doing an OS "Paste" function. Tweak as necessary and add error/exception checking as needed.
As a secondary, this code also places the file name on the clipboard so you can paste the file name into document editors.
package com.example.charles.clipboard;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class JavaToSystemClipboard {
public static void main(final String[] args) throws Exception {
final File fileOut = new File("someFileThatExists");
putFileToSystemClipboard(fileOut);
}
public static void putFileToSystemClipboard(final File fileOut) throws Exception {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
final ClipboardOwner clipboardOwner = null;
final Transferable transferable = new Transferable() {
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.javaFileListFlavor, DataFlavor.stringFlavor };
}
public Object getTransferData(final DataFlavor flavor) {
if (flavor.equals(DataFlavor.javaFileListFlavor)) {
final List<String> list = new ArrayList<>();
list.add(fileOut.getAbsolutePath());
return list;
}
if (flavor.equals(DataFlavor.stringFlavor)) {
return fileOut.getAbsolutePath();
}
return null;
}
};
clipboard.setContents(transferable, clipboardOwner);
}
}
You can write things by yourself using FileOutputStream and FileInputStream or you can used Apache Camel.