Wednesday, July 29, 2015

How to Read and Write from RandomAccessFile in Java

A FileInputStream lets you read data from a file whereas a FileOutputStream lets you write data to a file. A random access file is a combination of both. Using a random access file, you can read from a file as well as write to the file. Reading and writing using the file input and output streams are a sequential process. Using a random access file, you can read or write at any position within the file (hence the name random access). In this article, we'll try to see how to use RandomAccessFile with the help of an example.


An object of the RandomAccessFile class facilitates the random file access. It lets you read/write bytes and all primitive types values to a file. It also lets you work with strings using its readUTF() and writeUTF() methods. The RandomAccessFile class is not in the class hierarchy of the InputStream and OutputStream classes

Access Mode of Random access file
A random access file can be created in four different access modes. In its constructor, you must specify the access mode. The access mode value is a string. They are listed as follows:

  1. "r" : The file is opened in a read-only mode. You will receive an IOException if you attempt to write to the file.
  2. "rw" : The file is opened in a read-write mode. The file is created if it does not exist.
  3. "rws" : Same as the "rw" mode, except that any modifications to the file’s content and its metadata are written to the storage device immediately.
  4. "rwd" : Same as the "rw" mode, except that any modifications to the file’s content are written to the storage device immediately.

You create an instance of the RandomAccessFile class by specifying the file name and the access mode as shown:

RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");


File Pointer
A random access file has a file pointer that is advanced when you read data from it or write data to it. The file pointer is a kind of cursor where your next read or write will start. Its value indicates the distance of the cursor from the beginning of the file in byes. You can get the value of file pointer by using its getFilePointer() method. When you create an object of the RandomAccessFile class, the file pointer is set to zero, which indicates the beginning of the file. You can set the file pointer at a specific location in the file using the seek() method.

Length function
The length() method of a RandomAccessFile returns the current length of the file. You can extend or truncate a file by using its setLength() method. If you extend a file using this method, the contents of the extended portion of the file are not defined.


Reading from and writing to a random access file is performed the same way you have been reading/writing from/to any input and output streams.


Example 
Following example explain the use of a random access file. When you run this program, it writes two things to a file: the file read counter, which keeps track of how many times a file has been read using this program, and a text message of "Hello Java Latte". The program increments the counter value in the file every time it reads the file. The counter value keeps incrementing when you run this program repeatedly. You may get a different output every time you run this program.

I hope this example has given you the brief notion of Random Access File class and how it works.



If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...

63 comments:

  1. Java is highly professional course, and it helps students.Thanks for sharingJavaOnline Training Hyderabad

    ReplyDelete
  2. It is only through informative blogs like this that we will be able to understand lots of inner concepts of digital marketing.

    Selenium Training In Chennai

    Java Training In Chennai

    ReplyDelete
  3. great java tips At SynergisticIT we offer the best java bootcamp

    ReplyDelete
  4. Taking assignment help for your homework from allassignmenthelp.com is completely legit and in fact also very resourceful.
    online assignment help
    assignment help online

    ReplyDelete
  5. Due to using an outdated printer driver, you may experience loads of technical glitches while printing document. Therefore, if you get the Printer Offline error, ink cartridge issue, printer not printing problem and any other error issues, immediately check-out the driver installed in your operating system. If the driver is outdated, then open any browser and enter the URL 123.hp.com into the web search box. When you hit Enter and come on the Home Page, will notice there is a “Download” button for the upgraded version of printer driver. To click on that download button, the updated driver will begin downloading and automatically be saved in your system. Run the file as directed the driver will be successfully installed in your PC and hence won’t face kind of issues related to printer

    ReplyDelete
  6. Due to using an outdated printer driver, you may experience loads of technical glitches while printing document. Therefore, if you get the Printer Offline error, ink cartridge issue, printer not printing problem and any other error issues, immediately check-out the driver installed in your operating system. If the driver is outdated, then open any browser and enter the URL 123.hp.com into the web search box. When you hit Enter and come on the Home Page, will notice there is a “Download” button for the upgraded version of printer driver. To click on that download button, the updated driver will begin downloading and automatically be saved in your system. Run the file as directed the driver will be successfully installed in your PC and hence won’t face kind of issues related to printer.123.hp.com/setup
    123.hp.com
    Hp Printer Setup

    ReplyDelete
  7. Global Medical Textiles Market was valued at USD 16,686.6 million in 2018 and is projected to grow at a CAGR of 4.9% by 2025 owing to the rising geriatric population, ongoing technological advancements and stringent legislative framework mandating the use of medical textiles are expected to drive market over the forecast period. Rising awareness regarding new technologies for wound care, growing diabetic and aging population and support from the government in the form of funding non-implantable goods are widely being used worldwide, which is anticipated to propel the growth of the global market of medical textiles.

    ReplyDelete
  8. Since the Quick Utilities has introduced into the lives of people, payment system has revolutionized. Cash App card is one among many awesome features that contributed a lot to make the task of making instant payments safer and easier. Once you activate Cash card, you can sure of hassle-free payments all the time.

    For more info:- Activate cash app card | Cash app login

    ReplyDelete
  9. With the help of these simple steps, you can link Cash App card to PayPal account. You can use cash card details like a number & expiry date of your. To know more info: Cash App Card to Paypal
    Paypal To Cash App
    How to Add Money to Cash App Card

    ReplyDelete
  10. Cash App login process is all about getting an OTP from Cash App server for successful login to your Cash App account. More specifically, users can use either their email id or a registered phone number to get a security code from Cash App for successful sign in to Cash App account. Make sure that your device is well connected to the internet or Wi-Fi for error free login to Cashapp account.

    Get more info:- Delete cash app transaction history

    ReplyDelete
  11. If you are facing issues due to Comcast email login issues, with your Comcast email address and password. Click on users and preferences You should now be able to send or receive emails from people who need to reach you. If the problem exist, we suggest having your clients use a different email address instead of using Comcast email.

    ReplyDelete
  12. A thriving medical and healthcare industry, along with the rising awareness for healthcare practices among the consumers, is one of the key factors driving the Medical Textiles Market growth.

    ReplyDelete
  13. The report explores the dynamics that have a strong influence on the Diagnostic Wearable Medical Devices market and can also impact its future growth.

    ReplyDelete
  14. This was actually what I was looking for, and I am glad to came here! Thanks for sharing the such information with us.
    please visit my profile webcam test


    ReplyDelete
  15. Get a good deal of discounts and weekly coupons and cashback offer with Myperdiscohelp.com. MYOB accounting software price with us is extremely cheap and affordable. We offer a 40% discount coupon for new users and exciting offers from time to time. We guarantee an A+ grade in their assignments with our Ph.D. professor’s assistance.

    ReplyDelete

  16. Help For Assignments by Online

    Best assignment expert provides
    Help For Assignments Online to students who desire to get professional help and an A+ grade. We cover 100+ academic subjects to both school and college students.

    ReplyDelete
  17. event management. The main advantage of VR events over classic virtual events is pretty straightforward also It allows attendees/users to feel like they're in a physical environment with other people without actually being in the same physical space and which is clearly more immersive than interacting with others on a computer screen. how to write short biography examples and amazing ice breakers

    ReplyDelete
  18. To get Contract law assignment help online, you can visit the authority website of ABC Assignment Help, fill the prerequisite structure, enter the assignment cutoff time and send the subtleties to our specialists. Our specialists will hit you up with the valuing. You would then be able to continue further to complete your Contract law assignment on schedule. assignment help
    assignment provider

    ReplyDelete
  19. To understand programming, students have to work hard and devote all their time to education. However, often during their studies, students are faced with the need to hand over essays and other scientific papers on subjects that are completely unimportant for their future profession. The site https://www.customessaymeister.com/ has over 200 writers who will do all the hard work in a short time and at the highest level.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Here’s a little bit about me: I’m Amelia Charlotte with Cash App. Currently I am employed as a Manager at the cash app direct deposit pending. Occasionally, If you can get/find any type of questions about how to cash app direct deposit failed. If you have any questions, please contact us.

    Call us at + 1 (800) 523-7105

    Thank You

    ReplyDelete
  23. Connecting a printer over a USB cable is pretty easy. But connecting a wireless printer can become very challenging quite often. Follow the HP wireless printer setup process to install it in no time.

    1. Take the printer out of the box and remove all tapes from it before starting.
    2. Plug in the power cord, turn on the printer and install the print cartridges. Allow your printer to complete its startup routine, which includes printing of an alignment page (if applicable).
    3. Go to the manufacturer's website and download drivers for your printer model.
    4. Install the drivers and follow the instructions during hp wireless printer setup process.
    5. In the meantime, go to printer's control panel and use wireless printer setup wizard.
    6. Identify your wifi network and connect the printer to it using its correct credential.
    7. Complete the wireless printer setup process by connecting to your printer model as it would appear during installation.

    hp wireless printer setup

    ReplyDelete
  24. You can simply visit Amazon.com/mytv to link your Amazon Prime Video account to your streaming device.
    amazon.com/mytv
    amazon.com/redeem
    amazon.com/code
    amazon.com/mytv

    ReplyDelete
  25. Display box style is valuable for serving one or two tasty donuts. These display custom printed donut boxes can be perforated, which can easily be torn by the dotted line to take out one donut walking meanwhile. The other relatively best option for custom designer donut boxes is tuck end boxes.

    ReplyDelete
  26. This is absolutely the best information I have looking forward to get, and I must say that that you are doing a very nice job here in this fantastic blog. just keep it on, you are good. Checkout noun cut off mark for law

    ReplyDelete
  27. Thank you for posting such a great article. Keep it up mate.

    epanchayat telangana property tax

    ReplyDelete
  28. school of orthopaedic-cast-technology admission form, uith Thanks for sharing such great information with us. Very nice and well-explained article.

    ReplyDelete
  29. Regardless subject is bothering you greatly, in case you imagine that it's driving you insane, then, at that point, it's smarter to look for proficient internet based assignment help from our gifted essayists. They hold the executives degrees from renowned schools in Australia and have effectively conveyed huge number of assignments up until now. my assignment help

    ReplyDelete
  30. LABORATORY 6 Revised SPR 2017 An impurity in a sample of KClO3 Guided Inquiry 99 GENERAL INORGANIC question-hub.com CHEMISTRY I LABORATORY 6 An impurity in a sample of KClO3 OBJECTIVE: Scenario: The lab manager thinks that the KClO3 to be used in an experiment has been contaminated with KCl. Your task is to determine the extent of contamination (if any) by measuring the percent composition by mass of KCl in the …

    ReplyDelete
  31. Readers are always admiring informational blogs, and this is truly one of them. You did a great job. If you want to enhance writing skills, Sourceessay.com based assignment writer is the best solution for you. Online Assignment Help in Quebec

    ReplyDelete
  32. Thank you so much for sharing this wonderful content. In case, if you are currently unable to access the verizon mail. you need to visit down reporter blogs for more help
    Can't log into verizon email

    ReplyDelete
  33. Thank you for sharing this article. I really love it. in case, if you are dealing with the aol mail account. you need to visit down reporter blogs for more help.
    AOL old mail disappeared

    ReplyDelete
  34. Excellent! Our Experts provide best Nursing Assignment Help services to students and help them improve their nursing grades. Our nursing assignment writing service highlights your nursing assignment and enhances your nursing talents and abilities. Our nursing services are value, and you may get the best grade by choosing nursing assignments.

    ReplyDelete
  35. But he's trying none the less. I've been using Movable-type on a variety of websites for about a year and am nervous about switching to another platform. I have heard good things about . Is there a way I can import all my word press posts into it? Any help would be really appreciated!

    야한동영상
    립카페
    마사지블루
    출장마사지
    바카라사이트

    ReplyDelete
  36. if you are pursuing finance in Sydney and looking for Australian Assignment Help. There is no need to worry as many best assignment writers in Perth can craft your assignment within the deadline. The expert writers work 24/7 to help you craft assignments according to the university guidelines. You can avail of several benefits by availing the help of assignment experts:

    ReplyDelete
  37. I high appreciate this post. would you mind updating your blog with more information? I have blog Clicks Per Second (CPS) Rate. Use this tool and improve your Click Speed.

    ReplyDelete
  38. You’re a very skilled blogger, you have done really a fantastic job in putting up these amazing reads,  have joined your feed, and look forward to seeing more of your excellent post. ikcoed cut off mark for education and biology

    ReplyDelete
  39. This comment has been removed by the author.

    ReplyDelete
  40. I have to thank you for the time I spent on this especially great reading!! I really liked each part and also bookmarked you for new information on your site.
    룰렛사이트탑

    ReplyDelete
  41. Thanks for your auspicious write-up. I'm glad for being able to access through your contents. It’s a great joy visiting your blog. The contents of this blog are cool and very interesting. Visit here cibn past questions in pdf format

    ReplyDelete
  42. BookMyEssay is an organization that offers quality arrangements all things considered serious rates. If students asks for write my assignment for me then we provide all kind of writing services.
    https://www.bookmyessay.com/write-my-assignment-for-me/

    ReplyDelete
  43. Struggling with your assignments and need to submit them overnight? Don’t panic. SourceEssay offers instant assignment help to students. We have a team of professional writers who write customized content for students based on the quality parameters and guidelines provided by the university. Every assignment is unique and flawless and cross checked before they are delivered. For custom assignment writing service delivered by certified assignment writers join SourceEssay today.

    online assignment help Manchester
    online assignment help Leeds
    online assignment help Sheffield
    online assignment help croydon

    ReplyDelete
  44. m? I’d be very thankful if you may tricky a touch bit in addition. Admire it! I'm thinking about how i may be instructed at anything point another post has been made. I've subscribed for your rss which may do the trap? Have an notable day! 먹튀폴리스

    ReplyDelete
  45. i've been working on for the remaining 2 weeks. It was a difficult 2 weeks, however i am glad the paintings is achieved now. 먹튀폴리스

    ReplyDelete
  46. thank you, biomiracle merchandise p s is clearly charming perusing. I am glad i discovered this and had the possibility to understand it. Extremely good profession on this substance. I really like it. 카지노쿠폰

    ReplyDelete
  47. Eco Friendly Bitumen Market Increasing demand for sustainable roads and rapid development in roadway and highway construction activities are driving global eco-friendly bitumen market revenue growth

    ReplyDelete
  48. Are You Looking Forward To Figuring Out What Your Cash App Bank Name Is?
    Instead of going anywhere to determine the right kind of answer regarding your Cash App Bank Name you should directly move to the help section of cash app. One of the best things you will be able to enjoy is the right source of information along with effective remedies to fix each and every cassette issue permanently within the least time frame. Hence, you will be able to get the right clarification of your questions and start having a great answer to your query within a couple of seconds.

    ReplyDelete
  49. Forex Factory Calendar can be described as the best convenient and accurate calendar that keeps the track of news related to Forex. After this guide, you’ll be able to utilize the calendar and how interpret it in a manner that can benefit your trading.

    ReplyDelete
  50. These are really impressive ideas in regarding blogging. You have touched some fastidious things here. Anyways, keep up writing. Thank you for sharing. Also visit uba aptitude test past questions & solutions

    ReplyDelete
  51. Great work! I have also an article based on the to suggest. A color vision test, also known as the color blindness test, measures your ability to tell the difference between colors. If you don't pass this test, you may have color blindness. Visit it and please comment on your view.

    ReplyDelete
  52. Amazing! If you are thinking about well known Online Assignment Writer then must explore BookMyEssay to get helped by the top-rated professionals at affordable price.

    ReplyDelete
  53. Great post! If you are a businessman and want to Hire a Technical Writing Expert then you can explore Paperub. We have top professionals who can help you in your project at reasonable price.

    ReplyDelete
  54. I really appreciate you for posting such a useful content, defnectly will implement the points which you have mentioned in the blog. HippoCloud is the top-ranked software (IT) training facility in Vizag, where it teaches freshmen or students to become professionals as well as professionals to become subject matter experts in their chosen technologies

    ReplyDelete
  55. Thanks for posting your blog. Your content is really informative for us......

    Thanks
    Festive Décor Ideas

    ReplyDelete