Results 1 to 12 of 12
  1. #1
    viper110110 is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default Random File Access

    Hey guys I am trying to write a program that includes Random FIle access. I already have sequential, but this is a school assignment that wants sequential as well. I am completely clueless for how to start converting to random access.

    Do I have to make a new class?
    What is a constructor and how do I use/make one?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Random Access files are a little trickier to handle then regular text files or non random-access binary files. Are you required by your specification that you have to use these? Because if not, you may want to still use non-random access files.

    regarding writing a new class, it's hard to say given what you've told us. There are no hard rules that state that you must create a new class to deal with a different file, but if what you want to do is vastly different from what the original class is doing, it would be a good idea. Again, if you could give more information, we'd be able to help better. good luck.

  3. #3
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    There is a class in Java IO that is just exactly that, there is one and only one. Forget as soon as you can trying to do String conversions and so on, just write some bytes and read some bytes.

    I think ( not to be stupid ) it is called RandomAccessFile

    All other file types are not random access and this is random access but is only random access. You can go nuts trying to write ints and so on, conmpare this file type to DataOutputStream.

    Note also that hand-coding a byte array in Java is a pain in the bitch:
    Java Code:
    byte[] byteArray = {(byte) 5,(byte) 6,(byte) 7};
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Nicholas, would you agree that many times when users post here looking to user a RAF, they're better off using something else? That's why I want to know the specification before making specific recs.

  5. #5
    viper110110 is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    My assignment is
    # Revise the Peel Pet House (Module 3 - Part 3) program so that it uses Random Access File techniques instead of Sequential Access Files.
    Peel pet house is what I have already which includes file saving and reading using sequential techniques

    I also think I need to create a separate class to use as an object (a pet)

  6. #6
    viper110110 is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    I have pulled together what I can from the tutorial i have been given, and I have written the following:

    Java Code:
    import java.io.*;
    public class Pets
    {
        protected String breed; //30 bytes
        protected String category; //30 bytes
        protected double acqPrice; //8 bytes
        protected double sellPrice; //8 bytes
        protected double profit; //8 bytes
        protected static final int RECORD_SIZE = 84;
        
        public pets (RandomAccessFile input) throws IOException
        {
            byte [] breedBytes = new byte [30];
            input.readFully (breedBytes);
            breed = new String (breedBytes, 0);
        }
    }
    it is still incomplete, as I need to use the other variables

    also, what does .readFully do?

    my program already gets input from the user

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You're absolutely right and I'm wrong as the assignment leaves no doubt as to what you should use here.

    My reading of the API suggests that read and readFully differ in that read reads up to the number of bytes passed but may read less. It will return the number of bytes read. readFully reads the number of bytes passed (byte[].length) unless you run out of bytes (end of file) or hit an exception. It doesn't return anything.

  8. #8
    viper110110 is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    ok, from what I understand so far, I managed to scrape together some code. What does it do and how do I use it?:(

    Java Code:
    import java.io.*;
    public class Pets
    {
        protected String breed; //30 bytes
        protected String category; //30 bytes
        protected double acqPrice; //8 bytes
        protected double sellPrice; //8 bytes
        protected double profit; //8 bytes
        protected static final int RECORD_SIZE = 84;
        
        public Pets (RandomAccessFile input) throws IOException
        {
            byte [] breedBytes = new byte [30];
            input.readFully (breedBytes);
            breed = new String (breedBytes, 0);
            byte [] categoryBytes = new byte [30];
            input.readFully (categoryBytes);
            category = new String (categoryBytes, 0);
            acqPrice = input.readDouble();
            sellPrice = input.readDouble();
            profit = input.readDouble();
        }
        public Pets (String breed, String category, double acqPrice, double sellPrice, double profit)
        {
            this.breed = breed;
            this.category = category;
            this.acqPrice = acqPrice;
            this.sellPrice = sellPrice;
            this.profit = profit;
        }
        public void write (RandomAccessFile output) throws IOException
        {
            byte [] breedBytes = new byte [30];
            breed.getBytes (0, breed.length (), breedBytes, 0);
            output.write (breedBytes);
            byte [] categoryBytes = new byte [30];
            category.getBytes (0, category.length (), categoryBytes, 0);
            output.write (categoryBytes);
            output.writeDouble (acqPrice);
            output.writeDouble (sellPrice);
            output.writeDouble (profit);
        }
    }

  9. #9
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Post String.getBytes()

    Quote Originally Posted by Fubarable View Post
    Nicholas, would you agree that many times when users post here looking to user a RAF, they're better off using something else? That's why I want to know the specification before making specific recs.
    Basically, the question is difficult to provide definite answer. I wanted to get the poster going. I often look for posts with 0 replies and try to get them some momentum. In general, you are correct - that is why I directed attention to Data*Stream - to suggest to poster something that would cause poster to examine just how difficult the matter can be.

    read just calls readBytes
    Java Code:
        public int read(byte b[]) throws IOException {
    	return readBytes(b, 0, b.length);
        }
    Which returns int unless exception thrown, it's native so it depends on the implementation. ( probably )

    Code provided by poster looks remarkable for a few hours work, I suggest we demonstrate use of pointers or whatever we wish to call it to extract poster from hardcode. In general, I do not agree that always insisting on Streams and refusing something other than Streams leads to proficient coders, maybe good for some levels of work but I think student should grasp writing file in Binary.

    Probably what we need to do right this moment is:
    Java Code:
    byte[] breedStringByutes = String.getBytes();
    Which opie has wrong already, exactly the forbidden path. Not that that path is forbidden, it's the Uni-Stuff that will snag poster - which was what I was trying to skip over in my reply.


    Quote Originally Posted by viper110110 View Post
    ok, from what I understand so far, I managed to scrape together some code. What does it do and how do I use it?:(
    Is this computer science for art students or do you intend on gaining valuable experience? Most pupils not gain valued experience and really do not need it if just trying to work through some assignment. What the code does is split the constructor in a manner that makes the class resistant to devleopment.

    Then it has a write with no way to read in the files, and we need to know if
    Java Code:
    public static void main(String[] args)
    {
        ;//
    }
    is supposed to go in another area of the code. How many class files do you have and how do you run the program? Is it a GUI based program or a text-only?
    Last edited by Nicholas Jordan; 11-27-2008 at 10:35 AM.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  10. #10
    viper110110 is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    it is a text based program and this is the second class I have created for it

    I am using Holt's Ready To Program Java, which includes a run button that runs my code.

    Also, I plan to go into computer science in university and as a career, so I want to understand this. I understand the basic concept of RAF (look at one entry instead of opening them all) and I have done it in visual basic (I forget how though)

    I still don't quite understand how to use the code i've written

  11. #11
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    First things first: I want to to have a public book burning, advertise a week in advance in the local paper. Burn ALLVB books in your immediate 12-15' radius and keep it clear.

    When you have done that, I have some code I want you to write. Sorta simple actually, OCR in Java using AI

    Move to front-line research. How about this guy Pat, think we can use him?

    (joke - he will understand)
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  12. #12
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    Here, work on this:
    Java Code:
    class Rosetta
    {
        private String[] aac2145fff3d3a9 =
        {
            "In the reign of the young one who has succeeded his father in the kingship, lord of diadems, most glorious, who has established  Egypt and is pious towards the gods, triumphant over his enemies, who has restored  the civilized life of men, lord of the Thirty Years Festivals,  even as Ptah the Great, a king like Ra,  great king of the Upper and Lower countries, offspring of the  Gods Philopatores, one whom Ptah has approved, to whom Ra has  given victory, the living image of Amun, son of Ra, PTOLEMY, ",
            "LIVING FOR EVER, BELOVED OF PTAH, in the ninth year, when Aetos son of Aetos was priest of Alexander, and the Gods Soteres, and the  Gods Adelphoi, and the Gods Euergetai, and the Gods Philopatores  and the God Epiphanes Eucharistos; Pyrrha daughter of Philinos  being Athlophoros of Berenike Euergetis, Areia daughter of  Diogenes being Kanephoros of Arsinoe Philadelphos; Irene daughter of Ptolemy being Priestess of Arsinoe Philopator; the fourth of the month of Xandikos, according to the Egyptians the  18th Mekhir.  DECREE.  There being assembled the  Chief Priests and Prophets and those who enter the inner shrine  for the robing of the ",
            "gods, and the Fan-bearers and the Sacred Scribes and all the other priests from the temples throughout the land who have come  to meet the king at Memphis, for the feast of the assumption by PTOLEMY, THE EVER-LIVING, THE BELOVED OF PTAH, THE GOD EPIPHANES EUCHARISTOS, of the kingship in which he succeeded his father,  they being assembled in the temple in Memphis on this day  declared:  ",
            "Whereas King PTOLEMY, THE EVER-LIVING, THE BELOVED OF PTAH, THE GOD EPIPHANES EUCHARISTOS, the son of King Ptolemy and Queen  Arsinoe, the Gods Philopatores, has been a benefactor both to the  temple and to those who dwell in them, as well as all those who are his  subjects, being a god sprung from a god and goddess like Horus  the son of Isis and Osiris, who avenged his father Osiris,   being benevolently disposed towards  the gods, has dedicated to the temples revenues of money and corn  and has undertaken much outlay to bring Egypt into prosperity,  and to establish the temples, and has been generous with all his own means; and of the revenues  and taxes levied in Egypt some he has wholly remitted and others  has lightened, in order that the people and all the others might  be in prosperity during his reign; and whereas he has  remitted the debts to the crown being many in number which they  in Egypt and the rest of the kingdom owed; and whereas  those who were ",
            "in prison and those who were under accusation for a long time, he has freed of the charges against them; and whereas he has  directed that the gods shall continue to enjoy the revenues of  the temples and the yearly allowances given to them, both of  corn and money, likewise also the revenue assigned to the gods  from the vine land and from gardens and the other properties  which belonged to the gods in his father's time;  and whereas he directed also, with regard to the priests,  that they should pay no more as the tax for admission to the  priesthood than what was appointed them throughout his father's  reign and until the first year of his own reign; and has relieved  the members of the ",
            "priestly orders from the yearly journey to Alexandria; and whereas he has directed that impressment for the navy  shall no longer be employed; and of the tax on fine linen cloth  paid by the temples to the crown he  has remitted two-thirds; and whatever things were neglected in  former times he has restored to their proper condition, having a  care how the traditional duties shall be fittingly paid to the  gods;  and likewise has apportioned justice to all, like Thoth the great  and great; and has ordained that those who return of the warrior  class, and of others who were unfavourably  disposed in the days of the disturbances, should, on their return  be allowed to occupy their old possessions; and whereas he  provided that cavalry and infantry forces and ships should be  sent out against those who invaded  Egypt by sea and by land, laying out great sums in money and corn  in order that the temples and all those who are in the land might  be in safety; and having  gone to Lycopolis in the Busirite nome, which had been occupied  and fortified against a siege with an abundant store of weapons",
            "and all other supplies seeing that disaffection was now of long standing among the impious men gathered into it, who had  perpetrated much damage to the temples and to all the inhabitants  of Egypt, and having  encamped against it, he surrounded it with mounds and trenches  and elaborate fortifications; when the Nile made a great rise in  the eighth year of his reign, which usually floods the  plains, he prevented it, by damming at many points the outlets of  the channels spending upon this no small amount of money, and  setting cavalry and infantry to guard  them, in a short time he took the town by storm and destroyed all  the impious men in it, even as Thoth and Horus, the son of Isis  and Osiris, formerly subdued the rebels in the same  district; and as to those who had led the rebels in the time of  his father and who had disturbed the land and done wrong to the  temples, he came to Memphis to avenge  his father and his own kingship, and punished them all as they  deserved, at the time that he came there to perform the proper  ceremonies for the assumption of the crown; and whereas he  remitted what  was due to the crown in the temples up to his eighth year, being  no small amount of corn and money; so also the fines for the  fine linen  cloth not delivered to the crown, and of those delivered, the  several fees for their verification, for the same period; and he  also freed the temples of the tax of the measure1 of grain for  every measure2 of sacred land and likewise ",
            "the jar of wine for each measure2 of vine land; and whereas he bestowed many gifts upon Apis and Mnevis and upon the other  sacred animals in Egypt, because he was much more considerate  than the kings before him of all that belonged to  them; and for their burials he gave what was suitable lavishly  and splendidly, and what was regularly paid to their special  shrines, with sacrifices and festivals and other customary  observances,  and he maintained the honours of the temples and of Egypt  according to the laws; and he adorned the temple of Apis with  rich work, spending upon it gold and silver  and precious stones, no small amount; and whereas he has  funded temples and shrines and altars, and has repaired those  requiring it, having the spirit of a benficent god in matters  pertaining to  religion; and whereas after enquiry he has been renewing  the most honourable of the temples during his reign, as is  becoming; in requital of which things the gods have given him  health, victory and power, and all other good things,  and he and his children shall retain the kingship for all time.   WITH PROPITIOUS FORTUNE: It was resolved by the priests of  all the temples in the land to increase greatly the existing  honours of ",
            "King PTOLEMY, THE EVER-LIVING, THE BELOVED OF PTAH, THE GOD EPIPHANES EUCHARISTOS, likewise those of his parents the Gods  Philopatores, and of his ancestors, the Great Euergatai and  the Gods Adelphoi and the Gods Soteres and to set up in the most  prominent place of every temple an image of the EVER-LIVING  KING PTOLEMY, THE BELOVED OF PTAH, THE GOD EPIPHANES EUCHARISTOS, which shall be called that of 'PTOLEMY, the defender of Egypt,'  beside which shall stand the principal god of the temple, handing  him the scimitar of victory, all of which shall be manufactured  in the Egyptian  fashion;  and that the priests shall pay homage to the images  three times a day, and put upon them the sacred garments, and  perform the other usual honours such as are given to the other  gods in the Egyptian  festivals; and to establish for King PTOLEMY, THE GOD  EPIPHANES EUCHARISTOS, sprung of King Ptolemy and Queen  Arsinoe, the Gods Philopatores, a statue and golden shrine in  each of the ",
            "temples, and to set it up in the inner chamber with the other shrines; and in the great festivals in which the shrines are  carried in procession the shrine of the GOD EPIPHANES  EUCHARISTOS shall be carried in procession with them.   And in order that it may be easily distinguishable now and for  all time, there shall be set upon the shrine ten gold crowns of  the king, to which shall be added a cobra exactly as on all  the crowns adorned with cobras which are upon the other shrines,  in the centre of them shall be the double crown which he put on  when he went into the temple at Memphis  to perform therein the ceremonies for assuming the kingship; and  there shall be placed on the square surface round about the  crowns, beside the aforementioned crown, golden symbols eight in  number signifying  that it is the shrine of the king who makes manifest the Upper  and the Lower countries.  And since it is the 30th of Mesore on  which the birthday of the king is celebrated, and likewise the  17th of Paophi  on which he succeeded his father in the kingship, they have held  these days in honour as name-days in the temples, since they are  sources of great blessings for all; it was further decreed  that a festival shall be kept in the temples throughout Egypt on these days in every month, on which there shall be sacrifices  and libations and all the ceremonies customary at the other  festivals and the offerings shall be given to the priests who  serve in the temples.  And a festival shall be kept for King  PTOLEMY, THE EVER-LIVING, THE BELOVED OF PTAH, THE GOD EPIPHANES  EUCHARISTOS, yearly in the temples throughout the  land from the 1st of Thoth for five days, in which they shall  wear garlands and perform sacrifices and libations and the other  usual honours, and the priests in each temple shall be called  priests of the GOD EPIPHANES EUCHARISTOS in addition to  the names of the other gods whom they serve; and his priesthood  shall be entered upon all formal documents and engraved upon the  rings which they wear; ",
            "and private individuals shall also be allowed to keep the festival and set up the aforementioned shrine and have it in  their homes; performing the aforementioned celebrations  yearly, in order that it may be known to all that the men of  Egypt magnify and honour the GOD EPIPHANES EUCHARISTOS the  king, according to the law.  This decree shall be  inscribed on a stela of hard stone in sacred and native and Greek characters and set up  in each of the first, second and third rank temples beside the  image of the ever-living king."
        };
    }
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

Similar Threads

  1. Random access to text file
    By lunarbof in forum New To Java
    Replies: 1
    Last Post: 11-05-2008, 09:53 PM
  2. Cannot display a random string from .dat file
    By explosion242 in forum New To Java
    Replies: 2
    Last Post: 09-18-2008, 02:48 PM
  3. Update a record in Random access file
    By Rgfirefly24 in forum New To Java
    Replies: 2
    Last Post: 04-24-2008, 11:07 PM
  4. Random Access Files concept
    By AralX in forum New To Java
    Replies: 2
    Last Post: 12-25-2007, 08:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •