mp3 file path not playing from ArrayList? FileNotFoundException in Java - java

I am trying to create an MP3 player (console only at the moment) in Java. I have stored a list on track details (Name, Artist, Length, Genre, Pathway to the track e.g. "/Users/harvhead/Desktop/music.txt") in a text file and have used a method access() in my PlayMusic class to put all track details into separate ArrayLists. I have then inherited this Class into a RockMusic class and created a method to find any Rock music (genre) and then place the track pathway into a FileInputStream to then play the Rock Mp3.The problem is that even though the pathway is being passed correctly I am getting a FileNotFoundException (No such File or Directory). What am I doing wrong.????..please help..my code is below....I have spent hours banging my head against a wall trying to figure this out.
public class PlayMusic {
List<String> trackName = new ArrayList<String>();
List<String> artist = new ArrayList<String>();
List<String> length = new ArrayList<String>();
List<String> genre = new ArrayList<String>();
List<String> ID = new ArrayList<String>();
List<String> IDtrack = new ArrayList<String>();
List<String> trackPath = new ArrayList<String>();
File f = new File("/Users/harvhead/Desktop/music.txt");
File t = new File("/Users/harvhead/Desktop/musicTracks.txt");
public void access() throws FileNotFoundException {
Scanner sc = new Scanner(f);
try {
// reading each line of text and placing the 1st 2nd 3rd 4th element into different String Arraylist
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] details = line.split(",");
String trackN = details[0];
String artistN = details[1];
String trackLength = details[2];
String genreN = details[3];
String IDN = details[4];
String Pathtrack = details[5];
trackName.add(trackN);
artist.add(artistN);
length.add(trackLength);
genre.add(genreN);
ID.add(IDN);
trackPath.add(Pathtrack);
}
} catch (Exception e) {
System.out.println("Playlist Error");
}
if (trackName.isEmpty()) {
System.out.println("Arraylist is Empty");
} else {
System.out.println("ArrayList is not Empty");
}
}
Below is the method from my RockMusic Class:
public void rockPlayMusic() throws FileNotFoundException {
// call the access method (from PlayMusic Class) to create arraylists from txt file
access();
// finding Rock tracks and then trying to play them
for (int x = 0; x < genre.size(); x++) {
if (genre.get(x).contains("Rock")) {
try {
FileInputStream fis = new FileInputStream(trackPath.get(x));
System.out.println(trackPath.get(x));
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Below is my main:
package musicapp;
import java.io.FileNotFoundException;
public class MusicApp {
public static void main(String[] args) throws FileNotFoundException {
rockMusic rock = new rockMusic();
rock.rockPlayMusic();
}
}
Below is my error in the console:
ArrayList is not Empty
java.io.FileNotFoundException: "/Users/harvhead/Desktop/San Tropez.mp3" (No such file or directory)
java.io.FileNotFoundException: "/Users/harvhead/Desktop/Slave To The Wage.mp3" (No such file or directory)
java.io.FileNotFoundException: "/Users/harvhead/Desktop/Six Shooter.mp3" (No such file or directory)
java.io.FileNotFoundException: "/Users/harvhead/Desktop/Bones.mp3" (No such file or directory)
BUILD SUCCESSFUL (total time: 0 seconds)
This is the code for passing the file path manually into the FileInputStream and it plays the mp3 (I also got it to print the file path in the console).
public void manualPlayTest(){
try {
FileInputStream fis = new FileInputStream("/Users/harvhead/Desktop/San Tropez.mp3");
System.out.println("/Users/harvhead/Desktop/San Tropez.mp3");
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
Hardcoded path into rockPlayMusic method and this works fine.
public void rockPlayMusic() throws FileNotFoundException {
// call the access method (from PlayMusic Class) to create arraylists from txt file
access();
// finding Rock tracks and then trying to play them
for (int x = 0; x < genre.size(); x++) {
if (genre.get(x).contains("Rock")) {
try {
FileInputStream fis = new FileInputStream("/Users/harvhead/Desktop/San Tropez.mp3");
System.out.println(trackPath.get(x));
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
console output from hardcoded path in rockMusicPLay() method

Related

Java store specific csv value to list

The CSV look like this:
Name;Amount;Date
Netflix;5;1.1.2021
I want a different list for each expense, one for entertainment one for transport etc. However, I only want the amount to be stored on a list, how would I do that?
public class CsvReader {
public static void readDataLineByLine(String file) {
try {
// Create an object of file reader class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
// Read all data at once
List<String[]> allData = csvReader.readAll();
List<String> entertainment = new ArrayList<>();
// Print Data.
for (String[] row : allData) {
for (String cell : row) {
System.out.print(cell + "\t");
if (cell.startsWith("Netflix")){
entertainment.add(cell);
}
}
System.out.println();
System.out.println(entertainment);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CsvReader.readDataLineByLine("tt.csv");
}
}
If you use opencsv , how about writing the code like below? Please review.
public class CsvReader {
public static void readDataLineByLine(String file) {
try {
// Create an object of file reader class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
List<String> entertainment = new ArrayList<>();
// changed part
int index = 0;
while ((nextLine = reader.readNext()) != null) { // 2
// csv header exclusion condition
if(index == 0) {
continue;
}
String name = nextLine[0];
String amount = nextLine[1];
if (name.startsWith("Netflix")){
entertainment.add(amount);
}
index++;
}
// Print Data.
System.out.println();
System.out.println(entertainment);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CsvReader.readDataLineByLine("tt.csv");
}
}

How to display a text from a file on a WizardPage

I've been trying to read a text from a file and display it on my WizardPage.
It cannot be displayed but when I type the Text manually it shows the string.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Read_file {
// create ArrayList to store the information of a wizardPage
public List<Inventory> invItem = new ArrayList<>();
public read_file(String file_name) {
try {
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader(file_name));
// read the first line from the text file
String fileRead = br.readLine();
// loop until all lines are read
while (fileRead != null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] tokenize = fileRead.split(":");
// assume file is made correctly
// and make temporary variables for the three types of data
String Name = tokenize[0];
String Next = tokenize[1];
String Story = tokenize[2];
// creat temporary instance of Inventory object
// and load with three data values
Inventory tempObj = new Inventory(Name, Next, Story);
// add to array list
invItem.add(tempObj);
// read next line before looping
// if end of file reached
fileRead = br.readLine();
}
// close file stream
br.close();
}
// handle exceptions
catch (FileNotFoundException fnfe) {
System.out.println("file not found");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
This is my Wizard :
public class Wizard_main extends Wizard {
Page first;
Page third;
end End;
Read_file read=new Read_file("wizard.txt");
String story1=read.invItem.get(0).Story; // **this string cannot be displayed**
String story2="After a couple of hours, Jack woke up..."; //this one
works fine
public void addPages(){
first= new Page("S1",story1);
third=new Page("S2",story2);
End= new end("END");
first.setNextPage("S2", "S3");
third.setNextPage("S2", "S1");
addPage(First);
addPage(Third);
addPage(End);
}
#Override
public boolean performFinish() {
// TODO Auto-generated method stub
return true;
}}
I'm having "java.lang.IndexOutOfBoundsException" when I try to display a text from a file on my WizardPage.
Stack trace : !MESSAGE Unhandled event loop exception
!STACK 0
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
Note: The Text is properly displayed while using System.out.println() in another class
A solution which I used is as following :
private String getJsonFilePath(String fileName) {
String filePath = "";
// Reading file within the plugin
Bundle bundle = Platform.getBundle("com.eclipseplugin.sics");
// Get the wizard file from the plugin location.
URL fileURL = bundle.getEntry("lib/" + fileName + ".json");
try {
filePath = FileLocator.resolve(fileURL).getPath().substring(1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return filePath;
}
This is how FileLocator should be used.

ArrayOutofBoundsException - Attempting to read to/from file into Hash Map

I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)

Null pointer exception after using try/catch

I am still working on this same program. I though I was almost done after a suggestion in another thread that I implement a try/catch statement which worked well, however I am now getting a "Exception in thread "main" java.lang.NullPointerException at SimpleJavaAssignment.Company.main(Company.java:31)"
Code that triggers the exception:
File file = new File(Company.class.getResource("input.txt").getFile());
Complete code:
package SimpleJavaAssignment;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Company
{
ArrayList<Department> deptList = new ArrayList<Department>();
public Department checkDepartment(String name)
{
for(Department dept: deptList)
{
if(dept.getName().equals(name))
{
return dept;
}
}
Department d = new Department(name);
deptList.add(d);
return d;
}
public static void main(String[] args)
{
System.out.println ("This program will compile and display the stored employee data.");
Scanner inputFile = null;
File file = new File(Company.class.getResource("input.txt").getFile());
try {
inputFile = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Company c = new Company();
String input = inputFile.nextLine();
while(inputFile.hasNextLine() && input.length() != 0)
{
String[] inputArray = input.split(" ");
Department d = c.checkDepartment(inputArray[3]);
d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[0] + " " + inputArray[1], d);
input = inputFile.nextLine();
}
System.out.printf("%-15s %-15s %-15s %-15s %n", "DEPARTMENT", "EMPLOYEE NAME", "EMPLOYEE AGE",
"IS THE AGE A PRIME");
for(Department dept:c.deptList)
{
ArrayList<Employee> empList = dept.getEmployees();
for(Employee emp: empList)
{
emp.printInfo();
}
}
}
}
When you invoke Company.class.getResource("input.txt")
You are using the relative resource name, which is treated relative to the class's package. So, are you sure there is a file called input.txt at the same level of package SimpleJavaAssignment?
You could alternatively just specify the absolute path of the file and pass that into the File constructor, as such:
File file = new File("/my/path/input.txt");

Error while running customized java class

I have created a sequence file out of directory and then given index according to groups I want so that I can create groups using that index. This groups are then given one by one to my customized java class which gives information based on the file present in the group.
My problem is that some time it runs perfectly but some time gives different errors like null pointer exception, data type of field not found.
The problem is may be due to size of group. Because I am creating folder based group and then do the fetches the information from that folder inside my customized jar.
So how can I resolve this issue?
Below is my java class code:
public class OperateDirectory extends EvalFunc<DataBag>{
public TupleFactory tupleFactory = TupleFactory.getInstance();
public BagFactory bagFactory = BagFactory.getInstance();
public DataBag exec(Tuple input) throws IOException{
ArrayList<String> protoTuple = new ArrayList<>();
DataBag dataBag = bagFactory.newDefaultBag();
/* Create Directory */
if(input == null)
return dataBag;
if(input.size() != 2)
return dataBag;
long id = (long)input.get(0);
DataBag infoBag = (DataBag)input.get(1);
Iterator<Tuple> it = infoBag.iterator();
File dir = new File("/tmp/TestFolder"+id);
if(dir.exists())
{
FileUtils.cleanDirectory(dir);
}
else
{
dir.mkdir();
}
while(it.hasNext())
{
Tuple file_details = (Tuple)it.next();
if(file_details != null && file_details.size()==3)
{
String file_name = (String)file_details.get(1);
BytesWritable file_contents = (BytesWritable)file_details.get(2);
File f = new File(dir.getPath()+"/"+file_name);
f.deleteOnExit();
writeToFile(file_contents, f);
}
}
/* Perform operation here */
File f = new File("output"+id+".log");
ProcessBuilder performProcess1 = new ProcessBuilder("processes/processor", dir.getPath(),f.getPath());
Process process1 = performProcess1.start();
try
{
process1.waitFor();
if(f.exists() && f.length()>0)
{
ProcessBuilder performProcess2 = new ProcessBuilder("perl", "scripts/ParseFile.pl", f.getPath());
Process process2 = performProcess2.start();
InputStream is = process2.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
if(!line.isEmpty())
{
String [] tmpArray = line.split(",");
if(tmpArray.length == 2)
{
protoTuple.clear();
protoTuple.add(tmpArray[0]);
protoTuple.add(tmpArray[1]);
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
}
}
else
{
protoTuple.clear();
protoTuple.add("Error");
protoTuple.add("File "+f.getPath()+" does not exists ");
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
catch(Exception e)
{
protoTuple.clear();
protoTuple.add("Error ");
protoTuple.add(e.getMessage());
dataBag.add(tupleFactory.newTuple(protoTuple));
}
try
{
FileUtils.cleanDirectory(dir);
FileUtils.deleteDirectory(dir);
}
catch(Exception e)
{
}
return dataBag;
}
void writeToFile(BytesWritable value, File binaryFile) throws IOException{
FileOutputStream fileOut = new FileOutputStream(binaryFile);
fileOut.write(value.getBytes(), 0, value.getLength());
fileOut.close();
}
}

Categories