I'm trying to play a song from a folder that a user selects. Essentially, I am using my own Queue that I've created and I'm getting the right path.
Within the code below, I am using a Var called path. The path is "C:\Users\Shaun\Downloads\TestMusic\Ed Sheeran - Shape of You.mp3". When I define the path as just, "Ed Sheeran - Shape of You.mp3". It works! This tells me that this looks into the directory of where the project is started or runned from.
So, how do I make it play a file from any given directory?
The 'path' I'm referring to is below, " public void handlecentreButtonClick()".
public class graphicalController implements Initializable
{
//GUI Decleration
public Button centreButton;
public Button backButton;
public Button forwardButton;
public ToggleButton muteToggle;
public MenuItem loadFolder;
//Controller Decleration
String absolutePath;
SongQueue q = new SongQueue();
MediaPlayer player;
#Override
public void initialize(URL location, ResourceBundle resources)
{
centreButton.setStyle("-fx-background-image: url('/Resources/Play_Button.png')");
centreButton.setText("");
backButton.setStyle("-fx-background-image: url('/Resources/Back_Button.png')");
backButton.setText("");
forwardButton.setStyle("-fx-background-image: url('/Resources/Forward_Button.png')");
forwardButton.setText("");
muteToggle.setStyle("-fx-background-image: url('/Resources/ToggleSound_Button.png')");
muteToggle.setText("");
}
public void handlecentreButtonClick() {
if(!(q.isEmpty())) {
String file = q.peek().fileName.toString();
String path = absolutePath + "\\" + file;
Media song = new Media(path);
player = new MediaPlayer(song);
player.play();
}
}
public void handleforwardButtonClick() {
System.out.println("Hello.");
centreButton.setText("Hello");
}
public void handlebackButtonClick() {
System.out.println("Hello.");
centreButton.setText("Hello");
}
public void handleLoadButtonClick() {
DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory = directoryChooser.showDialog(null);
absolutePath = selectedDirectory.getAbsolutePath();
String path = absolutePath;
loadFilesFromFolder(path);
}
public void loadFilesFromFolder(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
while(!(q.isEmpty()))
{
try {Thread.sleep(500);}catch (Exception e){}
Song j = q.pop();
}
int listLength = listOfFiles.length;
for (int k = 0; k < listLength; k++) {
if (listOfFiles[k].isFile()) {
String fileName = listOfFiles[k].getName();
String fileNamePath = path + "\\" +fileName;
try {
InputStream input = new FileInputStream(new File(fileNamePath));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
String songName = metadata.get("title");
String artistName = metadata.get("xmpDM:artist");
String albumName = metadata.get("xmpDM:genre");
int id = k + 1;
Song newSong = new Song(id, fileName, songName, artistName, albumName);
q.push(newSong);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
}
}
Use
Media song = new Media(new File(path).toURI().toString());
I strongly recommend you construct the file in a platform independent way, however, instead of hard-coding a file separator specific to one particular file system. You can do
File path = new File(absolutePath, file);
Media song = new Media(path.toURI().toString());
With the help of #James_D...
You Cannot:
Media song = new Media("C:\Users\Shaun\Downloads\TestMusic\Ed Sheeran - Shape of You.mp3");
This will try and find the directory from the point of where you've launched your program.
Do:
Media song = new Media(new File(path).toURI().toString());
Related
I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}
I searched around but couldn't find nothing on this.
I would like to set the save (destination) path for a file selected in Filechooser. For example, I selected a picture called 'test.jpg', I would like for this 'test.jpg' to be saved to C:\blah\blah\blah\Pictures. How can I pull this off?
So far the code I have
public void OnImageAddBeer(ActionEvent event){
FileChooser fc = new FileChooser();
//Set extension filter
fc.getExtensionFilters().addAll(new ExtensionFilter("JPEG Files (*.jpg)", "*.jpg"));
File selectedFile = fc.showOpenDialog(null);
if( selectedFile != null){
}
}
All you need to do is copy the content inside the file choose in wherever you want, try something like this:
if(selectedFile != null){
copy(selectedFile.getAbsolutePath(), "C:\\blah\\blah\\blah\\Pictures\\test.jpg");
}
and the method copy:
public void copy(String from, String to) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(from);
fw = new FileWriter(to);
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
Basically copy just copy the content of the file located in from inside a new file located at to.
Try this:
String fileName = selectedFile.getName();
Path target = Paths.get("c:/user/test", fileName);
Files.copy(selectedFile.toPath(), target);
Add this statement if you want to set the destination path:
fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Pictures"));
Take this:
String dir = System.getProperty("user.dir");
File f = new File(dir + "/abc/def");
fc.setInitialDirectory(f);
I have a PDF in project location how to open pdf file
my project name is MyProject
My pdf is under project folder
MyProject\Pdf\test.pdf how to open my pdf file
I need to open pdf file in the project location
I have tried below code
final Button viewBtn= new Button("View Policy Schedule");
viewBtn.addClickListener( newButton.ClickListener() public void buttonClick(ClickEvent event) {
Window window = new Window();
window.setResizable(true);
window.setCaption("Claim Form Covering Letter PDF");
window.setWidth("800");
window.setHeight("600");
window.setModal(true);
window.center();
final String filepath = "Pdf//test.pdf";
File f = new File(filepath);
System.out.println(f.getAbsolutePath());
Path p = Paths.get(filepath);
String fileName = p.getFileName().toString();
StreamResource.StreamSource s = new StreamResource.StreamSource() {
/**
*
*/
private static final long serialVersionUID = 9138325634649289303L;
public InputStream getStream() {
try {
File f = new File(".");
System.out.println(f.getCanonicalPath());
FileInputStream fis = new FileInputStream(f);
return fis;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, fileName);
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.setContent(e);
UI.getCurrent().addWindow(window);
}
});
It's not working I have got a file not found exception
Move the PDF so you can read it from the classpath. If you are using Maven put it in src/main/resources. Otherwise put it in some package.
You can then read it using getResourcesAsStream() method of java.lang.class.
InputStream in = this.getClass().getResourcesAsStream("/test.pdf"); //classpath root
InputStream in = this.getClass().getResourcesAsStream("/my/package/name/test.pdf"); //from some package
Updated
final Button viewBtn= new Button("View Policy Schedule");
viewBtn.addClickListener( newButton.ClickListener()
public void buttonClick(ClickEvent event) {
Window window = new Window();
window.setResizable(true);
window.setCaption("Claim Form Covering Letter PDF");
window.setWidth("800");
window.setHeight("600");
window.setModal(true);
window.center();
StreamResource.StreamSource s = new StreamResource.StreamSource() {
public InputStream getStream() {
try {
return this.getClass().getResourcesAsStream("/test.pdf");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, fileName);
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.setContent(e);
UI.getCurrent().addWindow(window);
}
});
I have the following code to iterate over folders and files in the class path and determine the classes and get a field with a ID and print them out to a logger. This is working fine if I run this code in my IDE, but if I package my project into a JAR file and this JAR file into a EXE file with launch4j, I can't iterate over my classes again.
I get the following path if I try to iterate over my classes in the JAR/EXE file:
file:/C:/ENTWICKLUNG/java/workspaces/MyProject/MyProjectTest/MyProjectSNAPSHOT.exe!/com/abc/def
How can I achieve this to iterate over all my classes in my JAR/EXE file?
public class ClassInfoAction extends AbstractAction
{
/**
* Revision/ID of this class from SVN/CVS.
*/
public static String ID = "#(#) $Id ClassInfoAction.java 43506 2013-06-27 10:23:39Z $";
private ClassLoader classLoader = ClassLoader.getSystemClassLoader();
private ArrayList<String> classIds = new ArrayList<String>();
private ArrayList<String> classes = new ArrayList<String>();
private int countClasses = 0;
#Override
public void actionPerformed(ActionEvent e)
{
countClasses = 0;
classIds = new ArrayList<String>();
classes = new ArrayList<String>();
getAllIds();
Iterator<String> it = classIds.iterator();
while (it.hasNext())
{
countClasses++;
//here I print out the ID
}
}
private void getAllIds()
{
String tempName;
String tempAbsolutePath;
try
{
ArrayList<File> fileList = new ArrayList<File>();
Enumeration<URL> roots = ClassLoader.getSystemResources("com"); //it is a path like com/abc/def I won't do this path public
while (roots.hasMoreElements())
{
URL temp = roots.nextElement();
fileList.add(new File(temp.getPath()));
GlobalVariables.LOGGING_logger.info(temp.getPath());
}
for (int i = 0; i < fileList.size(); i++)
{
for (File file : fileList.get(i).listFiles())
{
LinkedList<File> newFileList = null;
if (file.isDirectory())
{
newFileList = (LinkedList<File>) FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
if (newFileList != null)
{
for (int j = 0; j < newFileList.size(); j++)
{
tempName = newFileList.get(j).getName();
tempAbsolutePath = newFileList.get(j).getAbsolutePath();
checkIDAndAdd(tempName, tempAbsolutePath);
}
}
}
else
{
tempName = file.getName();
tempAbsolutePath = file.getAbsolutePath();
checkIDAndAdd(tempName, tempAbsolutePath);
}
}
}
getIdsClasses();
}
catch (IOException e)
{
}
}
private void checkIDAndAdd(String name, String absolutePath)
{
if (name.endsWith(".class") && !name.matches(".*\\d.*") && !name.contains("$"))
{
String temp = absolutePath.replace("\\", ".");
temp = temp.substring(temp.lastIndexOf(/* Class prefix */)); //here I put in the class prefix
classes.add(FilenameUtils.removeExtension(temp));
}
}
private void getIdsClasses()
{
for (int i = 0; i < classes.size(); i++)
{
String className = classes.get(i);
Class<?> clazz = null;
try
{
clazz = Class.forName(className);
Field idField = clazz.getDeclaredField("ID");
idField.setAccessible(true);
classIds.add((String) idField.get(null));
}
catch (ClassNotFoundException e1)
{
}
catch (NoSuchFieldException e)
{
}
catch (SecurityException e)
{
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
}
}
}
You cannot create File objects from arbitrary URLs and use the usual filesystem traversal methods. Now, I'm not sure if launch4j does make any difference, but as for iterating over the contents of plain JAR file, you can use the official API:
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry e = entries.nextElement();
if (e.getName().startsWith("com")) {
// ...
}
}
Above snippet lists all the entries in the JAR file referenced by url, i.e. files and directories.
I'm taking HTML file and one XSLT file as input and generating HTML output but in my folder there are multiple HTML files and I've to take each of them as input and generate the corresponding output file while XSLT input file remains same every time. Currently in my code I'm repeating the code block every time to take the input HTML file. Instead of this I want to iterate over all the HTML files in the folder and take them as input file one by one to generate the output. In my current code file names are also fixed like part_1.html but it can vary and in that case this code won't work and this will create problem. Can anyone please help out in this matter:
Thanking you!
Current Java code (Sample for two files):
public void tranformation() {
// TODO Auto-generated method stub
transform1();
transform2();
}
public static void transform1(){
String inXML = "C:/SCORM_CP/part_1.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part1_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_1.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public static void transform2(){
String inXML = "C:/SCORM_CP/part_2.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part2_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_2.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
File dir = new File("/path/to/dir");
File[] htmlFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".html");
}
});
if (htmlFiles != null) for (File html: htmlFiles) {
...
}
You have to implement something like
public class Transformation {
public static void main (String[] args){
transformation(".", ".");
}
public static void transform(String inXML, String inXSL, String outTXT, String renamedFile){
System.out.println(inXML);
System.out.println(inXSL);
System.out.println(outTXT);
System.out.println(renamedFile);
}
public static void transformation(String inFolder, String outFolder){
File infolder = new File(inFolder);
File outfolder = new File(outFolder);
if (infolder.isDirectory() && outfolder.isDirectory()){
System.out.println("In " + infolder.getAbsolutePath());
System.out.println("Out " + outfolder.getAbsolutePath());
File[] listOfFiles = infolder.listFiles();
String outPath = outfolder.getAbsolutePath();
String inPath = infolder.getAbsolutePath();
for (File f: listOfFiles) {
if (f.isFile() ) {
System.out.println("File " + f.getName());
int indDot = f.getName().lastIndexOf(".");
String name = f.getName().substring(0, indDot);
String ext = f.getName().substring(indDot+1);
if (ext != null && ext.equals("html")){
transform(f.getAbsolutePath(), inPath+File.separator+name+".xsl", outPath+File.separator+name+".txt", outPath+File.separator+name+".html");
}
}
}
}
}
}
First you should write a method that take inXML, inXSL, outTXT and renamedFile as arguments.
Then, using the list() method of the File class, that eventually take a FilenameFilter, you may iterate over the files you want to transform.
Here is a sample of FilenameFilter :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains("part");
}
};
Regards
use DirectoryScanner which will make your job easier
Example of usage:
String[] includes = {"**\*.html"};
ds.setIncludes(includes);
ds.setBasedir(new File("test"));
ds.setCaseSensitive(true);
ds.scan();
System.out.println("FILES:");
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/DirectoryScanner.html