Hello, I am creating a basic Java program that will store music.

musicID
Track Name
Track Artist

I have chosen to do this through a text file, to store and view my data.

My text file output currently looks like this:

1
TrackName1
Artist1

2
TrackName2
Artist2

3
TrackName3
Artist3

Now, I need to be able to differentiate between each musicID to display the Track & Artist name appropriately into a GUI.

I have been told that I need to get Java to understand that a new line means that that's the end of the record and a new one begins. Is such a thing possible?

I need to be able to scroll through the records in a GUI.

I understand there must be easier ways to do this but we've been instructed to use TextFile I/O.

Thanks.

Recommended Answers

All 22 Replies

Yes, have your program read lines from the file.
When the line it reads from the file is empty, start a new record.

This usually means you're storing the records in a collection of some type, so when the new one is encountered, it does not destroy the old one.

How do I incorporate this into my GUI?

I have my write and read methods coded, but do not know how to tell java that when it reads the empty line, that's the end of the record.

So when I press (Next Track) it knows to move from musicID 1's data to musicID 2's data and so on.

Is your "record" a class, yet?

How do I incorporate this into my GUI?

I have my write and read methods coded, but do not know how to tell java that when it reads the empty line, that's the end of the record.

So when I press (Next Track) it knows to move from musicID 1's data to musicID 2's data and so on.

your GUI is your front-end code, handling the input is the back-end of your application.

String line = readNextLine();
if (line.trim().equals(""))
startNewRecord();
and continue that until there is no next line

how to tell java that when it reads the empty line, that's the end of the record.

Can you explain your problem here?
When the code reads an empty line, the code knows that it is at the end of the record and goes to do what ever needs to be done.

Hello, I am creating a basic Java program that will store music.

musicID
Track Name
Track Artist

I have chosen to do this through a text file, to store and view my data.

My text file output currently looks like this:

1
TrackName1
Artist1

2
TrackName2
Artist2

3
TrackName3
Artist3

Now, I need to be able to differentiate between each musicID to display the Track & Artist name appropriately into a GUI.

I have been told that I need to get Java to understand that a new line means that that's the end of the record and a new one begins. Is such a thing possible?

I need to be able to scroll through the records in a GUI.

I understand there must be easier ways to do this but we've been instructed to use TextFile I/O.

Thanks.

well adding to stultuske said, after you have read the first set of data up until the empty line "" then you can show the data you have just read, and when the user clicks again to transverse to the next song you just begin reading where you left off until the next empty ine and thats all there is, unless maybe there is something else wrong or thats giving you trouble if so what?

I am just having problems with navigating between each record using Next/Previous command buttons.

and when the user clicks again to transverse to the next song you just begin reading where you left off until the next empty ine

How does java know where to continue reading from?

Thank you so much for your help so far everyone, really do appreciate it.

Oh, sorry I was not aware that it stops reading after an empty line automatically.

I am just having problems with navigating between each record using Next/Previous command buttons.

How does java know where to continue reading from?

Thank you so much for your help so far everyone, really do appreciate it.

it wont stop reading but in the example stultuske gave you it detects a empty line and then you can handle it appropriately. And also if you use the getFilePointer() method in the RandomAccessFile class to get the current offset in the file. then you can use the RandomAccessFile to go directly to the number of the lines last read by utilizing the seek() method. check here for info on this api:http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

OK, so using:

String line = readNextLine();
if (line.trim().equals(""))

I can indicate to Java it's time to stop reading the file.

I will need to declare a variable to store the number of lines read.

Additionally, I will need to use RandomAccessFile in conjunction with the variable to access the next line.

Am I on the right lines here?

Thanks.

Using RandomAccessFile may add complexity.
Is this what you want to do:
begin loop
Read and save lines until an empty line.
Put all the saved lines in a class object (a record) and save that in a list
end loop

When done reading from the file, all the "records" are in the objects saved in the list.

{ clipped }Additionally, I will need to use RandomAccessFile in conjunction with the variable to access the next line.{ clipped }

No, you don't need a random access file.
I would use a BufferedReader

BufferedReader fileIn = new BufferedReader(new FileReader("{ filename goes here }"));

...that way you can use the .readLine() method to get strings from the file with relative ease.

OK, so using:

String line = readNextLine();
if (line.trim().equals(""))

I can indicate to Java it's time to stop reading the file.

I will need to declare a variable to store the number of lines read.

Additionally, I will need to use RandomAccessFile in conjunction with the variable to access the next line.

Am I on the right lines here?

Thanks.

you will need to use the RandomAccessFile class method getFilePointer() which will return the offset at which you are currently in the file, save this to a static variable and then the next time you want to begin reading from the line you left off you can use the seek() method along with the static variable at which you saved your last file position. so yup you are getting there :)

[EDIT] bufferedreader may be good also, and as for NormR1's comment i cant see it adding that much complexity-but hey i might be wrong :P?

Here is what I have so far:

public void addMusic() throws FileNotFoundException{
          PrintWriter outputStream = null;
          outputStream = new PrintWriter(new FileOutputStream(".//music.txt", true));
       try{
            {
           
                outputStream.println(musicIDTxt.getText());
                outputStream.println(trackNameTxt.getText());
                outputStream.println(artistNameTxt.getText());
                outputStream.println("");
                
                outputStream.close();
            }
                JOptionPane.showMessageDialog(null, "Music Saved Succesfully", "Information!", JOptionPane.OK_OPTION);
                clearClientText();
             }  catch(Exception e){
           
                JOptionPane.showMessageDialog(null, "Error, Music not saved", "Error!", JOptionPane.WARNING_MESSAGE);
           
       }
   }
public void  displayMusic() throws FileNotFoundException, IOException{
                
        try
        { 
           File DATAFILE = new File(".//music.txt");   
           FileInputStream DATA = new FileInputStream(DATAFILE);
           InputStreamReader DATASTREAM = new InputStreamReader(DATA);
           BufferedReader DATAREADER = new BufferedReader(DATASTREAM);
        
                 musicIDTxt.setText(DATAREADER.readLine());
                 trackNameTxt.setText(DATAREADER.readLine());
                 artistNameTxt.setText(DATAREADER.readLine());
                 DATAREADER.readLine(); //reads the empty line.
                 
                 
                 DATAREADER.close();
                 DATASTREAM.close();
                 DATA.close();
             
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "File I/O Error When Loading", "Error!", JOptionPane.WARNING_MESSAGE);
                 
       }        
        
    }

My Aim is:

[Program Load]
[GUI is filled with first record]
[Add New Music]
[GUI Cleared]
[Details Entered]
[Add Music Button Clicked]
[JTextField input stored to text file]
[First Record Re-Displayed]

As well as:

[Program Load]
[GUI is filled with first record]
_User wants to view music ID 2_
[User Clicks 'Next' Button]
[JTextField displays the next record (id/trackName/artistName) in the Text File]
[musicID 2 record displayed]

With a corresponding 'Previous' button too.

Thanks.

Can you add some looping to get it to read the entire file?

Here is what I have so far:

public void addMusic() throws FileNotFoundException{
          PrintWriter outputStream = null;
          outputStream = new PrintWriter(new FileOutputStream(".//music.txt", true));
       try{
            {
           
                outputStream.println(musicIDTxt.getText());
                outputStream.println(trackNameTxt.getText());
                outputStream.println(artistNameTxt.getText());
                outputStream.println("");
                
                outputStream.close();
            }
                JOptionPane.showMessageDialog(null, "Music Saved Succesfully", "Information!", JOptionPane.OK_OPTION);
                clearClientText();
             }  catch(Exception e){
           
                JOptionPane.showMessageDialog(null, "Error, Music not saved", "Error!", JOptionPane.WARNING_MESSAGE);
           
       }
   }
public void  displayMusic() throws FileNotFoundException, IOException{
                
        try
        { 
           File DATAFILE = new File(".//music.txt");   
           FileInputStream DATA = new FileInputStream(DATAFILE);
           InputStreamReader DATASTREAM = new InputStreamReader(DATA);
           BufferedReader DATAREADER = new BufferedReader(DATASTREAM);
        
                 musicIDTxt.setText(DATAREADER.readLine());
                 trackNameTxt.setText(DATAREADER.readLine());
                 artistNameTxt.setText(DATAREADER.readLine());
                 DATAREADER.readLine(); //reads the empty line.
                 
                 
                 DATAREADER.close();
                 DATASTREAM.close();
                 DATA.close();
             
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "File I/O Error When Loading", "Error!", JOptionPane.WARNING_MESSAGE);
                 
       }        
        
    }

My Aim is:

[Program Load]
[GUI is filled with first record]
[Add New Music]
[GUI Cleared]
[Details Entered]
[Add Music Button Clicked]
[JTextField input stored to text file]
[First Record Re-Displayed]

As well as:

[Program Load]
[GUI is filled with first record]
_User wants to view music ID 2_
[User Clicks 'Next' Button]
[JTextField displays the next record (id/trackName/artistName) in the Text File]
[musicID 2 record displayed]

With a corresponding 'Previous' button too.

Thanks.

yes yes thines01 came up with a great idea... taking it a step further, why not read the entire file at start up into either seperate arrays(flat array) or multidimensional array and then from there you can access each track by transversing through the array-downfall however is if the file is realllly big it may take some time to load them all? but then you could use a thread to load it and make sure all arrays are synchronized(but now thats a bit too far if you're a nOOb)

Can you add some looping to get it to read the entire file?

public void  displayMusic() throws FileNotFoundException, IOException{
 
        try
        { 
           File DATAFILE = new File(".//music.txt");   
           FileInputStream DATA = new FileInputStream(DATAFILE);
           InputStreamReader DATASTREAM = new InputStreamReader(DATA);
           BufferedReader DATAREADER = new BufferedReader(DATASTREAM);
 
while(DATAREADER != null) {
                 musicIDTxt.setText(DATAREADER.readLine());
                 trackNameTxt.setText(DATAREADER.readLine());
                 artistNameTxt.setText(DATAREADER.readLine());
                 DATAREADER.readLine(); //reads the empty line.
 }
 
                 DATAREADER.close();
                 DATASTREAM.close();
                 DATA.close();
 
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "File I/O Error When Loading", "Error!", JOptionPane.WARNING_MESSAGE);
 
       }        
 
    }

Do you mean something like that? Sorry, still very very novice at Java.

cOrRuPtG3n3t!x:

We were told to use Text Files, no mention of arrays so I do not know if that'll breach that. But I can't see them marking me down. If it is suitable for my problem I would love to implement it. Bearing in mind my level of Java knowledge would you deem it appropriate? This really does not need to be special, it just needs to function.

how you store your information physical (txt file) has nothing to do with how you store the information during the run of your application (arrays)

normally, working with arrays is one of the first things you learn, working with files usually comes later on, when you're more skilled.

public void  displayMusic() throws FileNotFoundException, IOException{
 
        try
        { 
           File DATAFILE = new File(".//music.txt");   
           FileInputStream DATA = new FileInputStream(DATAFILE);
           InputStreamReader DATASTREAM = new InputStreamReader(DATA);
           BufferedReader DATAREADER = new BufferedReader(DATASTREAM);
 
while(DATAREADER != null) {
                 musicIDTxt.setText(DATAREADER.readLine());
                 trackNameTxt.setText(DATAREADER.readLine());
                 artistNameTxt.setText(DATAREADER.readLine());
                 DATAREADER.readLine(); //reads the empty line.
 }
 
                 DATAREADER.close();
                 DATASTREAM.close();
                 DATA.close();
 
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "File I/O Error When Loading", "Error!", JOptionPane.WARNING_MESSAGE);
 
       }        
 
    }

Do you mean something like that? Sorry, still very very novice at Java.

cOrRuPtG3n3t!x:

We were told to use Text Files, no mention of arrays so I do not know if that'll breach that. But I can't see them marking me down. If it is suitable for my problem I would love to implement it. Bearing in mind my level of Java knowledge would you deem it appropriate? This really does not need to be special, it just needs to function.

oh no i got ahead of myself there forgetting its an assignment, rather keep it simple and functional...

and as for the while loop you included all that will do is make it read the file untile the end, and it will keep setting the textfields with the data it reads, however if you use it like that you will always end up with your last tack showing on your textfields

[EDIT] but as stultukse said above it would be much easier to work from an array then from the file the whole time

OK, I cannot see that breaching any rules.

How do I go about implementing what you've discussed?

Thanks.

OK, I cannot see that breaching any rules.

How do I go about implementing what you've discussed?

Thanks.

Here is some code to help you along as you had the idea but didnt know how to use it, from this i hope you will understand how to transverse between the array to fill your text boxes accordingly, i wont explain much in the code, have a look at how its working, all i can say is the for statement in the main should give you an idea how to transverse between arrays(when the button is clicked either next or previous you will add or minus 1 from a global integer which will help to transvserse the array using buttons):

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class test { 
    
    static String[] musicID = new String[100], trackName = new String[100], trackArtists = new String[100];

    public static void main(String[] args) {
        readfile("c:\\test.txt");
        for (int i = 0; i < musicID.length; i++) {
            if (musicID[i] != null) {//takes care of empty values in array if not filled completely
                System.out.println("music ID: " + musicID[i]);
                System.out.println("Track Name: " + trackName[i]);
                System.out.println("Track Artists: " + trackArtists[i]);
            }
        }

    }

    private static void readfile(String file) {
        int counter = 1, filler1 = 0, filler2 = 0, filler3 = 0;//used to keep track of the number of lines and arrays to fill in the same order and value
        try {
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream(file);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {

                if (!strLine.trim().equals("")) {
                    if (counter == 1) {//first line should have a track id
                        musicID[filler1] = strLine;
                        filler1++;
                        // System.out.println(strLine);
                    }
                    if (counter == 2) {//second line should be trackname
                        trackName[filler2] = strLine;
                        filler2++;
                        //  System.out.println(strLine);
                    }
                    if (counter == 3) {//this line will read the track artists
                        trackArtists[filler3] = strLine;
                        filler3++;
                        // System.out.println(strLine);
                    }
                    counter++;
                } else {//this is for when a new line occurs we must now reset our counter yo fill the arrays again in the right order i.e music id,track name and track artists
                    //  System.out.println("new line");
                    counter = 1;
                }
            }
            //Close the input stream
            in.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

the file i used for testing looks like this:

1
AA 
AAA

2
BB
BBB

3
CC
CCC

4
DD
DDD

5
EE
EEE

6
FF
FFF

That's absolutely incredible thank you so much.

Going to implement it right now, how do I give you maximum credit for your work on here? Mark solved and give you reputation?

That's absolutely incredible thank you so much.

Going to implement it right now, how do I give you maximum credit for your work on here? Mark solved and give you reputation?

Maximum credit came from your thanks :), check the bottom of this thread to mark as solved-it says 'Mark this thread as solved', and to give rep just click that up arrow on the side of this post/or any other and say 'add reputation' instead of 'no, just voting is fine'. Glad to be of help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.