Oracle OpenScript "Error reading file" when substituting variable - java

I'm composing a web script with Oracle OpenScript.
I recorded the actions to be performed
open link
select drop-down menu
select field from drop-down menu
save
and I'm trying to now substitute the link to be opened with a variable from a .csv I created in the assets but I get a "Error reading file" message.
SCREENSHOT
Here's the full code:
import oracle.oats.scripting.modules.basic.api.*;
import oracle.oats.scripting.modules.browser.api.*;
import oracle.oats.scripting.modules.functionalTest.api.*;
import oracle.oats.scripting.modules.utilities.api.*;
import oracle.oats.scripting.modules.utilities.api.sql.*;
import oracle.oats.scripting.modules.utilities.api.xml.*;
import oracle.oats.scripting.modules.utilities.api.file.*;
import oracle.oats.scripting.modules.webdom.api.*;
public class script extends IteratingVUserScript {
#ScriptService oracle.oats.scripting.modules.utilities.api.UtilitiesService
utilities;
#ScriptService oracle.oats.scripting.modules.browser.api.BrowserService
browser;
#ScriptService
oracle.oats.scripting.modules.functionalTest.api.FunctionalTestService ft;
#ScriptService oracle.oats.scripting.modules.webdom.api.WebDomService web;
public void initialize() throws Exception {
browser.launch();
}
/**
* Add code to be executed each iteration for this virtual user.
*/
public void run() throws Exception {
beginStep("[1] No Title (/hotelconfig.html)", 0);
{
web.window(2, "/web:window[#index='0' or #title='about:blank']")
.navigate(
"URL");
{
think(0.093);
}
}
endStep();
beginStep("[2] Working... (/wia)", 0);
{
web.window(4, "/web:window[#index='0' or #title='about:blank']")
.navigate(
"URL");
web.window(
5,
"/web:window[#index='0']")
.waitForPage(null);
{
think(6.198);
}
web.selectBox(
6,
"/web:window[#index='0']/web:document[#index='0']/web:form[#index='0']/web:select[(#id='office_id' or #name='office_id' or #index='10') and multiple mod 'False']")
.selectOptionByText(
"Office");
{
think(2.636);
}
web.button(
7,
"/web:window[#index='0']/web:document[#index='0']/web:form[#index='0']/web:input_submit[#name='save' or #value='Save' or #index='0']")
.click();
}
endStep();
beginStep(
"[3] Intranet - Property info - *Hotel Settings - *Hotel configuration (/hotelconfig.html)",
0);
{
web.window(
8,
"/web:window[#index='0']")
.waitForPage(null);
}
endStep();
}
public void finish() throws Exception {
}
}
I looked online and on Oracle's community but I couldn't find a fix.
I also tried to run the OpenScript Diagnosis Tool but no luck.
Anyone has any idea?

Oracle Application Testing Suite (OATS) best supports csv data sheet reading.
Code you pasted is just recording you performed and not seen any issue there. and Screenshot shows error message, something might have gone wrong while creating csv.
I can suggest external excel reader , which is inbuilt in OATS itself
http://www.testinghive.com/category/oracle-application-testing-suite-tips/
//Define Sheet name to be read, and provide comma seperated to read multiple sheets
String sheetName = "Sheet1";
//Mention excel sheet path
String strFile= "C:\\Demo\\test.xls";
//Defined array list to add Sheets to read
List sheetList = new ArrayList();
sheetList.add(sheetName);
// Iports Sheet1
datatable.importSheets(strFile, sheetList, true, true);
//get rowcount
info("Total rows :"+datatable.getRowCount());
int rowcount=datatable.getRowCount();
//Loop to read all rows
for (int i=0;i<rowcount;i++)
{
//Set current row fromw here you need to start reading, in this case start from first row
datatable.setCurrentRow(sheetName, i);
String strCompany=(String) datatable.getValue(sheetName,i,"Company");
String strEmpFName=(String) datatable.getValue(sheetName,i,"FirstName");
String strEmpLName=(String) datatable.getValue(sheetName,i,"LastName");
String strEmpID=(String) datatable.getValue(sheetName,i,"EmpID");
String strLocation=(String) datatable.getValue(sheetName,i,"Location");
//prints first name and last name
System.out.println("First Name : "+strEmpFName+", Last Name : "+strEmpLName);
//Sets ACTIVE column in excel sheet to Y
String strActive="Y";
datatable.setValue(sheetName, i, datatable.getColumn(sheetName, datatable.getColumnIndex("Active")), strActive);
}
//Updates sheet with updated values ie ACTIVE column sets to Y
datatable.exportToExcel("C:\\Demo\\test1.xlsx");
}
public void finish() throws Exception {
}
}

I find it easier to use a databank as data provider.
By adding a CSV file with the necessary variable, you will be able to do the following substitution:
public void run() throws Exception {
getDatabank("databank").getNextDatabankRecord();
String v_dataFilename = "{{db.databank.filename}}";
}

Related

How to get SQLite 'VACUUM' Progress

Is there a way to get the progress of sqlite 'VACUUM'?I am using this line of code here in Java:
connection1.createStatement().executeUpdate("VACUUM");
The User(MySelf & I) has to wait from some seconds to some minutes,i know that the actual .db file is being overriten with the help of a journal file that is created through the execution of the command.
Can i get an estimation using JAVA IO or something?Thanks for help..
No.
The SQLite C API has a progress handler, but it's probably not exposed by your Java driver, and the vacuum processing is implemented with a different mechanism that does not report the progress anyway.
You could try to look at the current size of the database file and of any temporary files, but it is practically impossible to get the name of the latter.
I found the answer to my question.So i know the size of the actual .db file and i wrote a Service in javaFX which calculates every 50 miliseconds the size of .db-journal file.So i check very frequently the size of journal file to see how of % is builded based on actual .db file:
package windows;
import java.io.File;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
/** Get the progress of Vacuum Operation */
public class VacuumProgress extends Service<Void> {
File basicFile;
File journalFile;
/**
* Starts the Vacuum Progress Service
*
* #param basicFile
* #param journalFile
*/
public void start(File basicFile, File journalFile) {
this.basicFile = basicFile;
this.journalFile = journalFile;
reset();
start();
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
System.out.println("Started...");
long bfL = basicFile.length();
while (!journalFile.exists()) {
Thread.sleep(50);
System.out.println("Journal File not yet Created!");
}
long jfL = journalFile.length();
while (jfL <= bfL) {
updateProgress(jfL = journalFile.length(), bfL);
Thread.sleep(50);
}
System.out.println("Exited Vacuum Progress Service");
return null;
}
};
}
}

Opening txt in sub directories with notepad through java

I've been browsing the site since yesterday and I can't see to find anything that answers my question, so I decided to just ask.
I'm making a pretty basic java GUI, it's designed to be run alongside files that wont be included in the actual java package for compatibility and easier customization of those files, I doubt they could be included either way as they have their own .jars and other things.
So, the problem I'm having is that the GUI application is in the main folder and I need it to locate and open txt files a couple sub-folders deep, in notepad without requiring a full file path as I'll be giving this project out to some people when it's done.
Currently I've been using this to open the files, but will only work for files in the main folder and trying to edit in any file paths did not work.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
Runtime rt=Runtime.getRuntime();
String file;
file = "READTHIS.txt";
try {
Process p=rt.exec("notepad " +file);
} catch (IOException ex) {
Logger.getLogger(NumberAdditionUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
if someone knows a way to do this, that'd be great.
On another note, I'd like to include the file shown above (READTHIS.txt) inside the actual java package, where would I put the file and how should I direct java towards it?
I've been away from java for a long time so I've forgotten pretty much anything, so simpler explanations are greatly appreciated.
Thanks to anyone reading this and any help would be awesome.
Update 2
So I added to the ConfigBox.java source code and made jButton1 open home\doc\READTHIS.txt in Notepad. I created an executable jar and the execution of the jar, via java -jar Racercraft.jar, is shown in the image below. Just take the example of what I did in ConfigBox.java and apply it to NumberAdditionUI.java for each of its JButtons, making sure to change the filePath variable to the corresponding file name that you would like to open.
Note: The contents of the JTextArea in the image below were changed during testing, my code below does not change the contents of the JTextArea.
Directory structure:
\home
Rasercraft.jar
\docs
READTHIS.txt
Code:
// imports and other code left out
public class ConfigBox extends javax.swing.JFrame {
// curDir will hold the absolute path to 'home\'
String curDir; // add this line
/**
* Creates new form ConfigBox
*/
public ConfigBox()
{
// this is where curDir gets set to the absolute path of 'home/'
curDir = new File("").getAbsolutePath(); // add this line
initComponents();
}
/*
* irrelevant code
*/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
Runtime rt = Runtime.getRuntime();
// filePath is set to 'home\docs\READTHIS.txt'
String filePath = curDir + "\\docs\\READTHIS.txt"; // add this line
try {
Process p = rt.exec("notepad " + filePath); // add filePath
} catch (IOException ex) {
Logger.getLogger(NumberAdditionUI.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
/*
* irrelevant code
*/
Update
This is the quick and dirty approach, if you would like me to add a more elegant solution just let me know. Notice that the file names and their relative paths are hard-coded as an array of strings.
Image of the folder hierarchy:
Code:
Note - This will only work on Windows.
import java.io.File;
import java.io.IOException;
public class Driver {
public static void main(String[] args) {
final String[] FILE_NAMES = {"\\files\\READTHIS.txt",
"\\files\\sub-files\\Help.txt",
"\\files\\sub-files\\Config.txt"
};
Runtime rt = Runtime.getRuntime();
// get the absolute path of the directory
File cwd = new File(new File("").getAbsolutePath());
// iterate over the hard-coded file names opening each in notepad
for(String file : FILE_NAMES) {
try {
Process p = rt.exec("notepad " + cwd.getAbsolutePath() + file);
} catch (IOException ex) {
// Logger.getLogger(NumberAdditionUI.class.getName())
// .log(Level.SEVERE, null, ex);
}
}
}
}
Alternative Approach
You could use the javax.swing.JFileChooser class to open a dialog that allows the user to select the location of the file they would like to open in Notepad.
I just coded this quick example using the relevant pieces from your code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Driver extends JFrame implements ActionListener {
JFileChooser fileChooser; // the file chooser
JButton openButton; // button used to open the file chooser
File file; // used to get the absolute path of the file
public Driver() {
this.fileChooser = new JFileChooser();
this.openButton = new JButton("Open");
this.openButton.addActionListener(this);
// add openButton to the JFrame
this.add(openButton);
// pack and display the JFrame
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// handle open button action.
if (e.getSource() == openButton) {
int returnVal = fileChooser.showOpenDialog(Driver.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// from your code
Runtime rt = Runtime.getRuntime();
try {
File file = fileChooser.getSelectedFile();
String fileAbsPath = file.getAbsolutePath();
Process p = rt.exec("notepad " + fileAbsPath);
} catch (IOException ex) {
// Logger.getLogger(NumberAdditionUI.class.getName())
// .log(Level.SEVERE, null, ex);
}
} else {
System.exit(1);
}
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Driver driver = new Driver();
}
});
}
}
I've also included a link to some helpful information about the FileChooser API, provided by Oracle: How to use File Choosers. If you need any help figuring out the code just let me know, via a comment, and I'll try my best to help.
As for including READTHIS.txt inside the actual java package, take a gander at these other StackOverflow questions:
Getting file from same package?
Reading a text file from a specific package?
How to include text files with executable jar?
Creating runnable jar with external files included?
Including a text file inside a jar file and reading it?

Setting pptx Theme in Java

I am trying to merge some pptx documents programmatically using java. I figured out how to do this in essence using Apache POI but the documents I am trying to merge do not work.
After significant searching and trial and error I figured out that the reason for this is that the pptx documents do not have theme information (i.e., if I click into powerpoint and check the slide master view it's blank). If I goto the themes in the Design Ribbon and select 'office theme' or another theme then save. the files will merge charmingly. Otherwise, I run into the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Failed to fetch default style for otherStyle and level=0
at org.apache.poi.xslf.usermodel.XSLFTextParagraph.getDefaultMasterStyle(XSLFTextParagraph.java:1005)
at org.apache.poi.xslf.usermodel.XSLFTextParagraph.fetchParagraphProperty(XSLFTextParagraph.java:1029)
at org.apache.poi.xslf.usermodel.XSLFTextParagraph.isBullet(XSLFTextParagraph.java:654)
at org.apache.poi.xslf.usermodel.XSLFTextParagraph.copy(XSLFTextParagraph.java:1044)
at org.apache.poi.xslf.usermodel.XSLFTextShape.copy(XSLFTextShape.java:631)
at org.apache.poi.xslf.usermodel.XSLFSheet.appendContent(XSLFSheet.java:358)
at com.apsiva.main.Snippet.main(Snippet.java:28)
The following is the code I ran:
package com.apsiva.main;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
public class Snippet {
/** Merge the pptx files in the array <decks> to the desired destination
* chosen in <outputPath> */
public static void main(String[] args) {
try {
FileInputStream empty = new FileInputStream("C:/Users/Alex/workspace/OutputWorker/tmp/base2.pptx");
XMLSlideShow pptx;
pptx = new XMLSlideShow(empty);
XSLFSlideLayout defaultLayout = pptx.getSlideMasters()[0].getLayout(SlideLayout.TITLE_AND_CONTENT);
FileInputStream is = new FileInputStream("C:/Users/Alex/workspace/OutputWorker/tmp/noWork.pptx");
// FileInputStream is = new FileInputStream("C:/Users/Alex/workspace/OutputWorker/tmp/works2.pptx");
XMLSlideShow src = new XMLSlideShow(is);
is.close();
for (XSLFSlide srcSlide: src.getSlides()){
pptx.createSlide(defaultLayout).appendContent(srcSlide);
}
FileOutputStream out = new FileOutputStream("C:/POI-TEST-OUTPUT.pptx");
pptx.write(out);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I want to get these files to merge and I believe the solution is to programmatically assign the theme to the files. How can it be done?
Thank you for your consideration!
In some cases when you have generated pptx files (ex. JasperReport exports) then some invalid values might be added for different fields. For example line spacing, which can be percent, and special characters, and the apache poi xslf doesn't know how to handle these values. When opening the file, PowerPoint automatically adjusts these values to valid ones. When using apache poi, you have to individually identify these fields and adjust them manually.
I had a similar issue, but with line spacing, and did a workaround, by setting the values for each paragraph like this:
List<XSLFShape> shapes = srcSlide.getShapes();
for (XSLFShape xslfShape: shapes) {
if (xslfShape instanceof XSLFTextShape){
List<XSLFTextParagraph> textParagraphs = ((XSLFTextShape) xslfShape).getTextParagraphs();
for (XSLFTextParagraph textParagraph: textParagraphs) {
textParagraph.setLineSpacing(10d);
}
}
}
This worked like a charm.
A more effective way to do this is to do it directly on the XML object:
List<CTShape> ctShapes = srcSlide.getXmlObject().getCSld().getSpTree().getSpList();
for (CTShape ctShape : ctShapes) {
List<CTTextParagraph> ctTextParagraphs = ctShape.getTxBody().getPList();
for (CTTextParagraph paragraph : ctTextParagraphs) {
if (paragraph.getPPr().getLnSpc() != null) {
paragraph.getPPr().unsetLnSpc();
}
}
}
/ApachePOI/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java
CTTextParagraphProperties getDefaultMasterStyle()
add
if( o.length == 0 ) {
return null;
}

Determining parameters on crawler4j

I am trying to use crawler4j like it was shown to be used in this example and no matter how I define the number of crawlers or change the root folder I continue to get this error from the code stating:
"Needed parameters:
rootFolder (it will contain intermediate crawl data)
numberOfCralwers (number of concurrent threads)"
The main code is below:
public class Controller {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
There was a similar question asking exactly what I want to know here , but I didn't quite understand the solution, like where I was to type java BasicCrawler Controller "arg1" "arg2" . I am running this code on Eclipse and I am still fairly new to the world of programming. I would really appreciate it if someone helped me understand this problem
If you aren't giving any arguments when you are running the file, you will get that error.
Put the following as comment sin your code or delete it.
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
And after that set your root folder to the one where you want to store the meta data.
To use crawler4j in your project you must create two classes. One of the them is CrawlController (Which start crawler according to the parameters) and the other is Crawler.
Just run the main method in the Controller class and see crawled pages
Here is Controller.java file:
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class Controller {
public static void main(String[] args) throws Exception {
RobotstxtConfig robotstxtConfig2 = new RobotstxtConfig();
System.out.println(robotstxtConfig2.getCacheSize());
System.out.println(robotstxtConfig2.getUserAgentName());
String crawlStorageFolder = "/crawler/testdata";
int numberOfCrawlers = 4;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
System.out.println(robotstxtConfig.getCacheSize());
System.out.println(robotstxtConfig.getUserAgentName());
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config,
pageFetcher, robotstxtServer);
controller.addSeed("http://cyesilkaya.wordpress.com/");
controller.start(Crawler.class, numberOfCrawlers);
}
}
Here is Crawler.java file:
import java.io.IOException;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.url.WebURL;
public class Crawler extends WebCrawler {
#Override
public boolean shouldVisit(WebURL url) {
// you can write your own filter to decide crawl the incoming URL or not.
return true;
}
#Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
try {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
}
catch (IOException e) {
}
}
}
In Eclipse :
->Click on run
->Click on run configurations...
In the pop-up window :
First, left column: make sure that your application is selected in sub-dir Java Application, else create a new (Click on new).
Then in the central Window, go on "Arguments"
Write your arguments under "Program arguments" Once you have written your first argument press enter for the seconde arguments, and so on... (=newline because args is a [ ])
Then click Apply
And click Run.

playing .mp3 file in java using notepad

I know this is a repeat question.
check original one here or here.
So my code is just the copy paste :
import javafx.scene.media.*;
class Gui {
public static void main(String[] args) {
try{
Media hit = new Media("skin.mp3");
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}catch(Exception e){
e.printStackTrace();
}
}
}
The exception which i'm getting is :
java.lang.IllegalArgumentException: uri.getScheme() == null!
at com.sun.media.jfxmedia.locator.Locator.<init>(Locator.java:217)
at javafx.scene.media.Media.<init>(Media.java:364)
at Gui.main(gui.java:6)
I'm compiling & running it correctly i.e. by including the jfxrt.jar file in classpath
Note: I'm just using notepad instead of any IDE.
So can anyone tell me the reason of IllegalArgumentException
Thankx
UPDATE : By using file://e:/skin.mp3 it worked fine but left me with another exception :
MediaException: MEDIA_INACCESSIBLE : e
at javafx.scene.media.Media.<init>(Unknown Source)
at Gui.main(gui.java:6)
So if you can put some light on this exception.
By the way i've checked the song, its not corrupt because it is playing nicely in vlc.
From the JavaFX API docs
The supplied URI must conform to RFC-2396 as required by java.net.URI.
Only HTTP, FILE, and JAR URIs are supported.
So, I suspect from reading the docs, you need to supply a URI path.
Something like file://path/to/file/skin.mp3 will probably work.
There are a few problems with the code in this question.
The class needs to be public.
JavaFX 2 applications need to extend the Application class.
JavaFX 2 applications should define a start method.
The locator for the media being created should be a full URI as noted by MadProgrammer.
Even though the question has a javafx-2 tag, I wonder if it is written for JavaFX 1.x JavaFX Script (which is now an unsupported programming language and incompatible with JavaFX 2). If so, I'd recommend coding in Java and using JavaFX 2.x for this rather than JavaFX Script.
On Windows a file representation of an absolute locator of a URI has three slashes after the file protocol. For example, the following is valid:
file:///C:/Users/Public/Music/skin.mp3
For some reason, a single slash will also work (I guess internally Java will interpolate the extra // for the protocol specifier on files or perhaps there is something I don't understand in the URL specification which means that you don't need a // after the protocol).
file:/C:/Users/Public/Music/skin.mp3
One way to check the file uri for something is valid to ask if the file uri exists
System.out.println("File " + filename + " exists? " + new File(filename).exists());
After you know your file uri is valid, you can convert it to a string using.
file.toURI().toURL().toExternalForm()
Here is a short sample program for playing some audio in JavaFX using a MediaPlayer with a little bit of error handling, so that it is easier to understand if something goes wrong.
import java.io.File;
import java.net.MalformedURLException;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.media.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/** plays an audio in JavaFX 2.x */
public class SimpleAudioPlayer extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) throws MalformedURLException {
final Label status = new Label("Init");
MediaPlayer mediaPlayer = createMediaPlayer(
"C:/Users/Public/Music/Sample Music/Future Islands - Before the Bridge.mp3",
status
);
StackPane layout = new StackPane();
layout.getChildren().addAll(status);
stage.setScene(new Scene(layout, 600, 100, Color.CORNSILK));
stage.show();
if (mediaPlayer != null) {
mediaPlayer.play();
}
}
/**
* creates a media player using a file from the given filename path
* and tracks the status of playing the file via the status label
*/
private MediaPlayer createMediaPlayer(final String filename, final Label status) throws MalformedURLException {
File file = new File(filename);
if (!file.exists()) {
status.setText("File does not exist: " + filename);
}
final String mediaLocation = file.toURI().toURL().toExternalForm();
Media media = new Media(mediaLocation);
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setOnError(new Runnable() {
#Override public void run() {
status.setText("Error");
}
});
mediaPlayer.setOnPlaying(new Runnable() {
#Override public void run() {
status.setText("Playing: " + mediaLocation);
}
});
mediaPlayer.setOnEndOfMedia(new Runnable() {
#Override public void run() {
status.setText("Done");
}
});
return mediaPlayer;
}
}
Here is a link to an additional example of a JavaFX 2.x media player which plays all of the mp3 files in a given directory sequentially.

Categories