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.
Related
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
I'm creating a program which handles SKU's. I currently have two classes in my program, the SKU class is the main class and a Store class in which an ArrayList is initialised and SKU objects are stored in the array. I currently have a method in my SKU class which takes input from a file, parses the data and stores the data using a String tokenizer in the objects variables and adds the objects to the array in the Store class. The problem I'm facing is that I'm wanting to separate the parsing method in the SKU class so that it simply reads from a line, and then have a separate method which takes a file input for the parser and finally update my Store class so that it initialises the products with the parsed data. Please, can you help me in regards to this?
My parsing method in the SKU class is currently as follows:
public void parser() {
try {
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader("products.txt"));
// read from first line from the text file
String fileRead = br.readLine();
// skip first line from sample file as it contains headings
int lineNumber = 0;
// loop until all lines are read
while (fileRead != null)
{
if(lineNumber == 0) {
lineNumber++;
continue;
}
lineNumber++;
// use string.split to load a string array with the values from each line of
// the file, using a tab as the delimiter
String[] tokenize = fileRead.split("\t");
// assume file is made correctly
// and make temporary variables for the three types of data
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
// create temporary instance of SKU object
// and load with three data values
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.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();
}
}
My Store class is as follows:
public class Store {
public static ArrayList<SKU> mySkuArrayList = new ArrayList<SKU>();
public void addSKU(SKU sku) {
mySkuArrayList.add(sku);
}
Split your code to three separate classes. SkuFile class represents text file where sku codes is stored, this class knows how to every sku entry stored and able to parse it. Sku class contains data. Store class contains
list of Sku and accept SkuFile in it's constructor.
class SkuFile {
private String path;
SkuFile(String path) {
this.path = path;
}
List<Sku> readAllSku() {
ArrayList<Sku> result = new ArrayList<>();
try {
List<String> lines = Files.readAllLines(new File(path).toPath());
for(String skuLine : lines) {
result.add(parseFrom(skuLine));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
private Sku parseFrom(String data){
String[] tokenize = data.split("\t");
productCode = tokenize[0];
description = tokenize[1];
price = new BigDecimal(tokenize[2]);
return new Sku(productCode, description, price);
}
}
class Sku {
private String code;
private String description;
private BigDecimal price;
Sku(String code, String description, BigDecimal price) {
this.code = code;
this.description = description;
this.price = price;
}
//getters setters methods
}
class Store {
private List<Sku> skus;
Store(SkuFile file) {
skus = file.readAllSku();
}
}
class Test {
public static void main(String[] args) {
Store store = new Store(new SkuFile("products.txt"));
}
}
One way to handle this is by making the parse method return a list of tokenizers(e.g. List tokenizeList) and a second method which takes that list as input and populates the SkuArrayList
Possible implementation of the parser method
public List<String[]> parser() {
List<String[]> tokenizeList = new ArrayList<>();
try {
... /*file opening logic*/
while (fileRead != null)
{
.../*line counting logic*/
String[] tokenize = fileRead.split("\t");
tokenizeList.add(tokenize);
fileRead = br.readLine();
}
// close file stream
br.close();
}// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return tokenizeList;
}
Possible implementation of the populate store method
public void populateStore(List<String[]> tokenizeList) {
for(String[] tokenize: tokenizeList) {
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
}
}
And the main method from where you call these two methods
public void foo() {
populateStore(parser());
}
I have this account creation program I'm working on, and would love to save the persons name, last name, email and password to a text file. The following snippet should do just that, but the error message I'm getting when I put a String variable in the .write method is, "no suitable method found for write(JTextFeild)".
private void signupActionPerformed(java.awt.event.ActionEvent evt) {
fname.getText();
lname.getText();
email.getText();
reemail.getText();
password.getText();
repassword.getText();
if(male.equals(true)) {
males = true;
}
if(female.equals(true)) {
females = true;
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("UserPass.txt"));
writer.write(fname);
}
catch ( IOException e) {
}
finally {
try {
if ( writer != null) {
writer.close( );
}
}
catch ( IOException e) {
}
}
}
Any ideas on how to fix this?
From the documentation of getText() in javax.swing.text.JTextComponent:
public String getText()
JTextField is just the GUI element, getText() doesn't change it.
You should store the result in a String variable and then use it to write().
I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.
Ok so I'm a noob at Java and this just got me.
I have a button that calls a class in which some background code runs to check if the tape drive is online, offline or busy.
Button Code:
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
Then I have my separate class file btnRunBackup.
public class btnRunBackup{
public void checkStatus(){
/*
Here I simply create a tempfile and run some
linux commands via getRuntime and print the
output to the tempfile
Then I call my second method passing the
absolute file path of the tempfile
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
Here I use BufferedReader to go through the
tempfile and look for as series of 3
different strings.
I use a if else if statement for flow control
depending on what string was found.
string 1 will call a new Jframe
if string 2, 3 or none of them are found the
is where I am stuck at
}
}
I want to return a String value back to btnRunBckActionPerformed().
The reason is lblRunBck will initially show no text at all but for instance the user clicks on the button and the resource happens to be busy then i want to run lblRunBck.setText(param); on lblRunBck while refusing the user permission to continue
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text;
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
here is my btnRunBackup class
public class btnRunBackup {
private String s;
public void checkStatus() {
String s, path = null;
Process p;
try{//try1
//create a temp file named tempfilexxx.tmp
File temp = File.createTempFile("tempfile", ".tmp");
//get file path
path = temp.getAbsolutePath();
System.out.println("checkStatus: " + path);
//write to tempfilexxx.tmp
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
try{// try2
//set p = to the content of ls home
p = Runtime.getRuntime().exec("ls /home | grep ariel");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
//write content of p to tempfilexxx.tmp line by line
while ((s = br.readLine()) != null)
bw.write(s + "\n");
//close BufferedReader
br.close();
}catch (Exception e){} //END OF try2
//close BufferedWriter
bw.close();
/*
Now that we ran the 'mt -f /dev/nst0 status command under home we
will filter for one of the following strings
(for testing we will use ls -la /home and filter for ariel)
We will do this by calling the checkStatus method
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
}// END OF try1
}// END OF listDir
//throws FileNotFoundException for bufferedReader if file not found
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
On production code there will be 4 possible conditions:
1. ONLINE - ready to write (currently we will use ariel)
2. DR_OPEN - no tape available
3. /dev/nst0: Device or resource busy - resource bussy
4. If other than stated above give error 1000
*/
System.out.println("statusControl: " + param);
String ONLINE = "arielvz",
OPEN = "DR_OPEN",
BUSSY = "Device or resource busy",
sCurrentLine;
//Scan file line by line for one of the above options
BufferedReader br = new BufferedReader(new FileReader(param));
while ((sCurrentLine = br.readLine()) != null){
//Tape is online and ready for writing
if (sCurrentLine.contains(ONLINE)){
System.out.println("found ariel");
}
//There is no tape in the tape drive
else if (sCurrentLine.contains(OPEN)){
//lblRunBck should tell the user to put a tape in the drive
System.out.println("No tap in tape drive");
}
else if (sCurrentLine.contains(BUSSY)){
//lblRunBck should notify user that the resource is in use
System.out.println("Device or resource bussy");
}
else{
//Something unexpected happend
System.out.println("Error 1001: Please notify Administrator");
}
}
}//END OF statusControl
public String returnHandler(String param){
return param;
}
}
Maby This will make it more clear
If you want checkStatus to return a status, then do not make it returning nothing (a void function)
public class btnRunBackup {
private String s;
public void checkStatus() {
but make it returning error as a String like:
public class btnRunBackup {
private String s;
public String checkStatus() {
String error = null; // by default no error
... do whatever you need to find out the error
....
error = "error is: xxx ";
return error; // return null (no error ) or what you found
}
change you logic in you calling code to display what error have been returned by checkStatus
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
String error;
btnRunBackup runBackupObject = new btnRunBackup();
error = runBackupObject.checkStatus();
lblRunBck.setText(error == null ? "No error" : error);
}