How to read properties file in Java.

Reading properties file in Java is much easier than you might have thought. Following example illustrates one simple way of reading properties from a properties file.

Let’s say we need to read from myConfig.properties file.


The properties file has following entries.

Directory = C:/prodFiles/
NumberOfFiles = 25
Extension = java

Here is the java code to read the values of these keys.

import java.util.Properties;
import java.io.*;
public class ReadValues{
   private static final String PROP_FILE="myConfig.properties";
   public void readPropertiesFile(){
       try{
  	     InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
	     Properties prop = new Properties();
             prop.load(is);
	     String directory = prop.getProperty("Directory");
             String numberOfFiles = prop.getProperty("NumberOfFiles");
	     String  fileExtension = prop.getProperty("Extension");
             is.close();
	  /* code to use values read from the file*/
       }catch(Exception e){
         System.out.println("Failed to read from " + PROP_FILE + " file.");
       }
   }
  }

The code is quite simple and self explanatory. Let me know if you have any questions.

Comments 82

  • Well done. I appreciate the fact that you didn’t assume everyone knew how to read in a properties file with Java. It’s a simple task but worth the post. Thanks.

    Bret’s last blog post..Windows XP to Remain Available Until 2010

  • Thanks!

  • hi coud u plz tell me where u put your .properties file

  • Vivek, you can put your properties file in any directory as long as that directory is in your classpath. For e.g; if you save your properties file under C:\resources directory make sure that C:\resources is in your classpath. Or you can put your properties file in the same directory where you have your class file.

  • For web applications we can put the .properties file inside your src folder so that after build all the properties file gets reflected/copied to /WEB-INF/classes folder.

    To access you can use following code snippet:

    Properties props = new Properties();
    try
    {
    ClassLoader cl = UploadDealDocs.class.getClassLoader();
    InputStream fin = cl.getResourceAsStream.(“./config.properties”);
    props.load(fin);
    uploadedFilePath = props.getProperty(“localDrivePath”);
    fin.close();
    }
    catch (Exception e1)
    {
    LOG.info(“FILE CANNOT BE READ”);
    e1.printStackTrace();
    }

    Cheers 🙂

  • Is there a different format for reading URL values from the properties file?

    My property file has

    targetUrl=https://foobar:9080/foo

    I am getting a malformed exception error. Do you think I am missing something?

    Also, how do we read integer values from the properties file?

  • Rashmi, you don’t have to do anything special to read the URL from properties file. Follow the example I provided and you should be able to read the URL from the file. If you can share your code I’ll be glad to help you with malformed exception.
    To read an integer value you read the value from the file as String and then convert that value to an int using valueOf method of the Integer class. In my example I read numberOfFiles from the file, here is how you can convert that to an int.
    String numberOfFiles = prop.getProperty(“NumberOfFiles”);
    int number = Integer.valueOf(numberOfFiles);

    Hope this helps, otherwise feel free to contact me directly.

  • Hi Zaheer,
    it’s excellent one. i was trying with file input stream as shown below, but application unable to catch the file. getting file not found exception, after replacing these with your above eg. now it is working fine. thank you very much.
    and may i know the fault in my below code, y i am getting errror ??

    File propsFile = new File(filePath);
    FileInputStream fileInputStream = new FileInputStream(propsFile);
    prop.load(new FileInputStream(“db.properties”));
    System.out.println(“Driver Name : “+prop.getProperty(“driverName”));

  • Hai Friends,

    i need more clarification regarding the properties file and how to retrive the values from the properties to a java file.
    and provide more examples

  • Hai
    provide more examples

  • Cna we read from properties file without using InputStream. I mean I want asingle line access to key in properties file through my swings program.

  • @Rashim

    I think you have to escape “:” and “=”. So the new line in your properties file would be:
    targetUrl=https\://foobar:9080/foo
    Hope this helps.

  • Nice, but how do you read integer values? Or doubles, floats, etc… Can it only read string values?

  • Retrieve data from property file specially for database connection

    Get Database connection parameters from property file

  • This article is very useful…Thanks…

  • The old soldiers pointed out Shazai which means I have committed a sin for which I apologise but the emperor refused to utter it.
    Here are a few new interesting to say the jdm tow hook is 1.

    Of course, a battery. Until I searched Kelly Blue Book, KBB, prices the vehicles you are researching.
    The Jdm Tow Hook Camry is invented so that engine sound levels are maintained at a minimum below the bonnet.

  • I was excited to find this site. I wanted to thank you for ones time for this fantastic read!! I definitely loved every bit of it and i also have you bookmarked to look at new information in your blog.

  • Howdy! This post couldn’t be written much better! Going through this post reminds me of my previous roommate! He always kept talking about this. I will send this information to him. Pretty sure he will have a good read. Thank you for sharing!

  • Post writing is also a fun, if you be acquainted with afterward you can
    write if not it is complex to write.

  • This is my first time pay a visit at here and i am actually impressed to read all at alone place.

    Also visit my page; health

  • Tengo mucho de tiempo leyendo su web

  • Mayy I just sayy what a relief tto uncover somebody that
    actually knows what they are discussing over the internet.

    You certainly know how to bring an issue to light and maske it important.
    A lot more people should check this out and understand this
    side of the story. I was surprisesd you aren’t more popular because you certainly have the gift.

    Also visit my blog post … humidors

  • It’s not my first time to go to see this site, i am visiting this site
    dailly and obtain pleasant data from here everyday.

  • Very rapidly this website will be famous among all blogging
    visitors, due to it’s pleasant posts

  • I always emailed this blog post page to all my associates, for the reason
    that if like to read it afterward my friends will too.

  • I have to thank you for the efforts you have put in penning this site.
    I’m hoping to view the same high-grade content
    from you later on as well. In fact, your creative writing abilities has motivated me
    to get my very own site now 😉

  • Hi Dear, are you actually visiting this site regularly, if so
    afterward you will definitely get nice know-how.

  • Excellent blog here! Also your site loads up very fast!
    What web host are you using? Can I get your affiliate link to your
    host? I wish my website loaded up as fast as yours lol

  • Everyone loves what you guys are usually up too.

    Such clever work and coverage! Keep up the excellent works guys I’ve incorporated you
    guys to my own blogroll.

  • My partner and I stumbled over here different website and thought I should check things out.
    I like what I see so i am just following you.
    Look forward to finding out about your weeb page again.

    Look into my site; vendita casette (http://casetteinlegnodagiardino.net/)

  • A person essentially lend a hand to make seriously articles I would state.
    This is the first time I frequented your website page and thus far?

    I amazed with the analysis you made to make this particular submit amazing.
    Wonderful process!

    Here is my web site … kulup

  • Un sitio web super trabajado felicidades

  • Thanks for the marvelous posting! I actually enjoyed reading it, you may
    be a great author. I will be sure to bookmark your blog and will eventually come back someday.
    I want to encourage that you continue your great writing, have a nice day!

  • You really make it appear really easy along with your presentation however I to find this topic to be really something that I believe I’d never understand.

    It kind of feels too complex and very vast for me. I’m looking forward on your
    next submit, I will attempt to get the hang
    of it!

    Also visit my weblog – six guns hack

  • I tend not to drop many comments, however i did some searching and wound up here How to
    read properties file in Java.. And I actually do have a few questions for you
    if it’s allright. Could it be simply me or does it
    appear like some of the comments appear like
    left by brain dead individuals? 😛 And, if you are writing at additional
    online sites, I would like to follow everything fresh
    you have to post. Could you list of every one of all your public sites
    like your linkedin profile, Facebook page or twitter feed?

    my weblog: bau ketiak

  • Normally I don’t read article on blogs, but I would like to
    say that this write-up very forced me to try and do it!
    Your writing style has been surprised me.
    Thank you, very great post.

    Take a look at my web-site … keputihan

  • I think the admin of this website is genuinely working hard in support of his web page, for the reason that here every data is
    quality based material.

    my webpage – endometriosis

  • naturally like your web site but you have to take a look at the spelling on several of your
    posts. A number of them are rife with spelling issues and I find it
    very bothersome to tell the reality however
    I’ll surely come again again.

    Feel free to surf to my website :: Micro G Pen

  • Thank you a lot for sharing this with all folks you really understand what you are speaking approximately!
    Bookmarked. Please additionally talk over with my site =).
    We can have a link exchange contract among us

    Take a look at my web blog – huong dan hack dragon city tren facebook

  • Thankfulness to my father who stated to me about this website, this
    web site is genuinely remarkable.

    Here is my web blog; minecraft pe maps

  • This article presents clear idea for the new people of blogging, that truly how to do blogging and site-building

  • I love your blog.. very nixe colors & theme. Did you design this website yourself or
    did you hire someone to do iit for you? Plz answer back as I’m looking to construct myy own blog and would like to kniw where u got
    this from. many thanks

    my web page; throne rush hack facebook

  • Hi, i feel that i noticed you visited my weblog
    thus i got hhere to return the desire?.I am attepting to
    in finding things to enhance my site!I guess its good enough to make use off
    a few oof your ideas!!

    Here is my weblog drag racing hack ios

  • Fantastic website. Plenty of helpful information here. I am sending
    iit to some friends ans also sharing inn delicious. And
    naturally, thank you ffor your effort!

    My webpage; league of angels hack – dailymotion.com,

  • Unquestionably believe that which you stated. Your favorite justification sedemed to bbe on the
    net the easiest thing to bbe aware of. I say to you, I definitely get annoyed while people consider
    worries that they plainly don’t know about. You
    managed to hit tthe nail upon the top as well as defined out
    the whole thing without having side effect ,
    people could take a signal. Will probably be back to get more.
    Thanks

    Here is my web-site … csr racing hack android

  • Hello to all, how is the whole thing, I think every one is getting more from this web
    page, and your views are fastidious in favor of new visitors.

    My web site: Grand Theft Auto 5 KeyGen Free Download

  • Hello! I Just Wanted To Ask If You Ever Have Any Trouble With Hackers? My Last Blog (wordpress) Was Hacked And I Ended Up Losing Several Weeks Of Hard Work Due To No Back Up. Do You Have Any Solutions To Stop Hackers?

  • Good day I am so excited I found your website, I reakly found you
    by error, while I was browsing on Askjeeve for omething else, Anyhow I am here now
    and would just like to say thankis a lot for a marvelous post and a all round interesting blog (I also love the theme/design), I don’t have time to read through it all at thhe minute butt I have book-marked
    it andd also added your RSS feeds, so whesn I have time I will bbe back to
    read much more, Please do keep up the great jo.

    Alsso visit my homepage throne rush hack facebook

  • In any circumstance, it really is searching really very good on all fronts.
    The Oranje, despite their defensive lapses, have established to
    be a next fifty percent group that will capitalize on any possibilities they get.
    Spain’s possession recreation looked one hundred occasions sharper against the Germans than it did in opposition to Portugal (1st half
    specifically) and Paraguay, and how the Dutch responds to that is likely to figure out the impact their attack has
    on Ilker Casillas’ fortress. Wesley Sneijder demands one particular a lot
    more large match. Robin Van Persie requirements to uncover
    the back again of the web at least after. We could be seeking at 1 of the most entertaining finals because France-Brazil in ’98.

    The 2014 Cameroon staff is seeking to bounce back
    again this year with support from Puma, who unveiled their forthcoming World Cup package before these days.
    The package characteristics a environmentally friendly based home jersey with some of the most elaborate depth to date from World Cup
    kits. The jersey contains the Cameroon crest as
    effectively as the nation’s mascot, The Indomitable Lion, over the coronary heart.
    The away jersey features the identical patches and crest but is
    accomplished in the yellow found on their nation’s flag and consists
    of crimson accents on the shoulders and Puma brand.

  • I needed to thank you for this great read!! I certainly enjoyed every little bit of it.
    I’ve got you book marked to check out new things you post…

    Feel free to surf to my web-site drag racing hack android;
    http://encipecom.metodista.br/mediawiki/index.php/Usu%C3%A1rio:DeandreSpinks,

  • Hey would you mind stating which blog platform you’re using?
    I’m going to start my own blog soon but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking for something unique.

    P.S My apologies for getting off-topic but I had to ask!

  • If you wish for to improve your familiarity just keep
    visiting this web page and be updated with the hottest gossip
    posted here.

  • I’m really impressed with your writing skills and also with the layout on your
    weblog. Is this a paid theme or did you modify it yourself?
    Anyway keep up the excellent quality writing, it’s rare to
    see a nice blog like this one today.

    Feel free to visit my website … Parallel Desktop 9 Activation Key

  • Hiya. Great website. I’m wondering, though,
    where did you get the theme? Or did you produce
    it for yourself? I’m getting started on my own website and am
    on the lookout for a theme as cool as this one. Thanks so much.

  • Hey! I know this is kinda off topic but I was wondering which blog platform
    are you using for this site? I’m getting tired of WordPress because I’ve had
    issues with hackers and I’m looking at alternatives for another platform.

    I would be awesome if you could point me in the direction of a good platform.

    my blog my free zoo cheats

  • Geile meiden
    Geile meiden zoeken sex vandaag in Breda. Ik heb namelijk niet
    veelal zin om stad en natie af te zwerven. U kan toch hopelijk wel
    lekker dicht in de buurt zijn? Het liefste immers een partner waar ik op de rijwiel
    naartoe zou kunnen. Of een vent die zo lief is om mij op te zoeken.
    Ik heb een huiselijk huis met een mooie tuin. Ook een slaapkamer die ik recentelijk geleden helemaal heb laten verbouwen.

    Geile meisjes voor seks

    Spijtig ben ik tot op heden de enkele geweest die deze slaapkamer heeft mogen adoreren. Mogelijk wil jij
    dan eens het licht uitdoen, de gordijnen dichtschuiven, de kussens opschudden en mij daar komen begeleiden?
    Dat zou toch buitengewoon zijn? Ik houd overigens erg van romantische sex net als vele andere geile meiden.
    Allicht na een zinderende striptease wil ik je ook langzaam van je outfit ontdoen en hoop dat we in het
    begin een hele tijd van een massage kunnen gaan genieten voordat
    we verder gaan. Kusjes zijn hopelijk toch heel
    welkom bij jou? Waarschijnlijk dat je het ook wel plezierig vindt als ik met je tepels
    speel? De mijne zijn erg gevoelig, daar mag je zeker ook mee spelen,
    fijn hoor, als je eerst mijn setje uitgetrokken hebt.
    En is het dan een logische vervolgstap dat we elkaar met onze
    mond gaan verwennen? Ik schijn goed te kunnen pijpen, wellicht dat ik je daarvan mag overtuigen? Zeker hoop ik dan dat ik van jouw
    befkunsten mag gaan plezier hebben. Ik heb gevoelige lipjes, maar mijn klitje is pas echt
    gevoelig. Prachtig als je dan met het puntje van je
    tong mij daar tot een hoogtepunt probeert te brengen en net
    voordat ik klaarkom weer een beetje terugtrekt. Ik weet dat het wat ontwikkelen zal zijn allemaal,
    maar op een gegeven ogenblik dienen we toch wel opsporen wat
    we gemakkelijk vinden en op welk moment we op het punt staan klaar te komen? Ik denk dat de
    meeste geile meisjes standje 69 daar heel geschikt voor is.
    Wij hebben het nu trouwens over geile activiteiten in de slaapkamer, maar zou het ook niet heftig zijn om eens sex in de openlucht te ondervinden?
    Door mij ook zeker sex gezocht in een plantsoen of in een steegje.
    Dat is toch weer eens wat anders? Zullen we er lekker snel dan van gaan smullen? Mag ik
    verlangen dat jij ook sex zoekt en dat je me helemaal gek zult maken?

  • I know this if off topic but I’m looking into starting my own weblog and
    was wondering what all is needed to get setup? I’massuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m noot 100% sure. Any recommendations or advice
    would be grratly appreciated. Many thanks

    Visit my bblog :: iron force hack android

  • Excellent post. Keep posting such kind of information on your page.
    Im really impressed by your blog.
    Hello there, You have done an excellent job.
    I will certainly digg it and for my part recommend to my
    friends. I am sure they will be benefited from this site.

    Also visit my web-site … website (http://eisenhowermemorial.gov/)

  • Every weekend i used to pay a visit this web page, because i want enjoyment, as this this
    web page conations truly pleasant funny data too.

  • I was excited to find this page. I wanted to thank you for your time for this
    particularly wonderful read!! I definitely liked every
    little bit of it and i also have you saved to fav to see new
    stuff on your website.

  • Saya sangat senang untuk menemukan situs ini pada google.I ingin mengucapkan banyak terima kasih kepada Anda berkaitan dengan posting ini luar biasa!

  • This paragraph will help the internet people for building up new weblog or even a blog from start to end.

    My website: RoTMG Hack

  • Hurrah, that’s what I was seeking for, what a stuff!
    present here at this weblog, thanks admin of this web
    page.

  • It is perfect time to make some plans for the longer term and it’s time to be
    happy. I have learn this put up and if I may I want to suggest you some fascinating things
    or suggestions. Perhaps you can write next articles regarding this article.
    I want to read more issues approximately it!

  • Great info. Lucky me I found your website by chance (stumbleupon).

    I’ve bookmarked it for later!

  • Tremendous things here. I’m very glad to look your article.
    Thanks a lot and I’m taking a look ahead to touch you.

    Will you please drop me a e-mail?

    Feel free to visit my web page :: attorney criminal in Coventry

  • Thiss is vry interesting, Yoou are a very skilledd blogger.
    I have joined your feed and stay up for seeking extra of ykur great post.
    Additionally, I have shared your web site in my social
    networks

    Look at my blog: REBEL8 MLTD Coupon code – Rowena

  • With havin so much content do you ever run into any problems of
    plagorism or copyright infringement? My site has a lot of completely
    unique content I’ve either authored myself or outsourced but it appears a lot of it is popping it up all over the web without my agreement.
    Do you know any ways to help reduce content from being
    stolen? I’d truly appreciate it.

  • It’s not my first time to visit this site, i am browsing this web page
    dailly and take good information from here daily.

  • I am in fact grateful to the holder of this web page who has shared this enormous post at at this time.

    Here is my web site – MLTD (Sherrie)

  • WOW just what I was looking for. Came here by searching for comment home

  • whoah this weblog is great i really like reading your posts.

    Keep up the good work! You already know, a lot of individuals are hunting around for this information,
    you can aid them greatly.

  • Great blog! Do you have any tips for aspiring
    writers? I’m hoping to start my own site soon but
    I’m a little lost on everything. Would you propose starting with a free
    platform like WordPress or go for a paid option? There are so
    many options out there that I’m totally overwhelmed ..
    Any tips? Thank you!

  • Hi, I wish for to subscribe for this website to take most recent updates,
    thus where can i do it please assist.

  • I have read so many content regarding the blogger lovers except this piece of writing is truly a good article, keep it up.

  • Thank you for another great article. The place else may just anyone get that type of
    information in such a perfect way of writing? I’ve a presentation subsequent week,
    and I’m on the search for such info.

  • It’s amazing to go to see this web site and reading the views of all mates regarding this article,
    while I am also eager of getting experience.

  • This paragraph will help the internet users for creating new
    webpage or even a weblog from start to end.

  • If some one needs to be updated with most up-to-date technologies after
    that he must be go to see this site and be up to date daily.

  • Everyone loves what you guys are usually up too.
    Thiss sort of cleverr work and exposure! Keep up the
    fantastic works guys I’ve incorporated you guyts to mmy blogroll.

Leave a Reply

Your email address will not be published. Required fields are marked *