How to read from properties file

Hi,
I am using JSR 168.
while creating a new portlet, a folder gets created with the name as "portlet". Under which is resource package and <PortletName>Bundle.java.
pls tell me how to read from .properties file.
waiting eagerly for some reply
Thanks & Regards,
HP
Edited by: user9003827 on Apr 13, 2010 3:42 AM

I think i have mixed it up :)
I have looked at it again and believe you are using regular JSP portlets.
Can you tell what you want to achieve by reading .properties file. Are you meaning the preferences of the portlet or what exactly are you trying to do?
Reading propertie files is easy:
// Read properties file.
Properties properties = new Properties();
try {
    properties.load(new FileInputStream("filename.properties"));
    String myKey = properties.getProperty("yourKey");
} catch (IOException e) {
}Edited by: Yannick.O on 13-Apr-2010 05:52

Similar Messages

  • How to read the properties file available in Server File structure in webdy

    hi all,
    I have developed one webdynpro application. In this application i need to access mdm server to continue. For getting the connection i need to pass the IP addresses.
    Can i have code  how to read the properties file which is residing in the server file. with out included along with the application. keeping some where in the file structure in the server. I want to read that properties file by  maintain the iP addresses and users in  properties file based on the key i want to read like below.
    servername="abcServer"
    username="john"
    password="test123"
    Please send me the code how to read this properties file from the file structure and how to read this values by key  in webdynpro application
    Regards
    Vijay

    Hi Vijay,
    You can try this piece of code too:
    Properties props = new Properties();
    //try retrieve data from file
    //catch exception in case properties file does not exist
    try {
             props.load(new FileInputStream("c:\property\Test.properties")); //File location
             String serverName = props.getProperty("servername"); //Similarly, you can access the other properties
             if(serverName==null)
               //....do appropriate handling
         }     catch(IOException e)
                   e.printStackTrace();
    Regards,
    Alka.

  • Help: Servlet can't read from properties file

    I am working on a web application running in Tomcat on Linux.My java source file reads some parameters from a properties file (data.properties)in the same directory. This works well in a simple application. However, if it is used in the Tomcat environment, it can't be read by a servlet file (LoginServlet.java). I put both the "LoginServlet.class" and "data.properties" in the following directory: /webapps/myapp/WEB-INF/classes. When I run the web application in Tomcat, the error is "data.properties not found". What is the problem? Do I need to modify my "web.xml" and/or Tomcat's "server.xml"? If so, how to modify them?
    This web application contains a lot of serlets. So I don't want to hardcode the parameters into the servlet codes.
    Any info will be appreciated. Thanks in advance!:)

    Putting the properties file in webapps/myapp may or may not help.
    My assumption is that you are trying to open the file by brute force, with something like
    InputStream propis = new FileInputStream ("data.properties");
    Properties props = new Properties ( );
    props.load (propis);
    What you want is to have the class loader find a file in the same place as the class file, and give you back an input stream reading from that file, which you can then pass to the Properties.load(InputStream) method. This is called a "resource," and the way to do it is:
    InputStream propis = getServletContext().getResourceAsStream("data.properties");
    // remaining code as above
    This will cause the class loader for the servlet context (a/k/a the Web application) to find the file in the same manner as it might find a class, but instead of treating it as compiled JVM code, and loading it, it simply passes you back an InputStream from which you do whatever you want.
    Cheers!
    Jerry Oberle
    perl -e 'printf "mailto%cg%s%cearthlink%cnet\n", 58, "oberle", 64, 46;'

  • How to read from a file line by line

    Hi
    I am new to using LabView and was wondering how I could read data from a text file one line at a time and display this data one line at a time as well. I tried looking through the Reading from Text File . vi example but that just seems to be reading and displaying everything together.
    Thanks
    -Karan

    Hi
    My aim is to read text line by line and to then go ahead and display the last 8 reaad lines of code to give the impression of text falling down a screen. I tested the first while loop and that seemed to work fine. However, when I encounter an EOF, I would like the text already read to keep making its way down the screen and keep inputting NULL characters into the array to simulate the effect of the text falling down the screen which is why I created the second while loop. I tried to input the NULL characters using a box for ENUM constants. However, I kept getting an error saying the data types do not match. What would I need to do? For the display I plan on putting indicators next to the 8 places where the text would be stored which I have not done so far.
    I am also attaching a copy of the error.
    Thanks
    -Karan
    Attachments:
    DisplayText.vi ‏40 KB
    Error.JPG ‏89 KB
    PictureOfBlock.JPG ‏120 KB

  • How to read from text file?

    I would like to read data (frequencies) already written in a text file. I will need read these frequencies one at a time to set the function generator (as part of my data acquisition application), acquire data that is in turn written to a file and then go back and read the next frequency from the file to repeat the process again. I also have another idea of doing the same, which is read all the frequencies from the text file and populate a table and a frequency value is picked from the table each time to go through the process mentioned above.
    Can anyone suggest the following: (1) How to read from a text file, (2) What could be the most efficient way of solving my above problem.
    I am a new LabVIEW user and any help will be appreciated.

    Hi Research,
    Depending on the format of the data file, there are a few options for reading it.  If it is tab delimited, you may want to use the Read from SpreadSheet File VI which will read the file into an Array.  You can then use the Index Array VI to pull out individual entries.  If the files is ASCII but not tab delimited, you could use the regular Open File and Read File VIs.  You can either read the file out piece by piece, or read the entire file into a string and then use the Match Pattern VI to parse out the different elements (there are actually many ways to do this - check out the Strings subpalette). 
    Since you're new to LabVIEW, you may want to check out these resources:
    Three Hour Introduction to LabVIEW
    Six Hour Introduction to LabVIEW
    Getting Started with LabVIEW
    I hope this helps!  Let us know if you have more questions,
    Megan B.
    National Instruments

  • How to Read from a file UTL_FILE.

    I have created a file.
    Now i need to read it. I have used following code, but at the time of execution i am getting error, ORA-065-012, & ORA-29283.
    I am giving path as /oracle/PRD/dataload
    and file_name is as CREATE_FILE_TESTING.TXT
    the procedure is as -
    CREATE OR REPLACE PROCEDURE pms_generate_file
    path VARCHAR2,
    file_name VARCHAR2
    IS
    file_handle UTL_FILE.FILE_TYPE;
    v_text VARCHAR(4000);
    BEGIN
    file_handle := UTL_FILE.FOPEN(path, file_name, 'R');
    UTL_FILE.GET_LINE (file_handle, v_text);
    DBMS_OUTPUT.PUT_LINE(v_text);
    UTL_FILE.FCLOSE (file_handle);
    END;
    Regards,
    AgrawalV

    And you immediately used the Oracle documentation and found that
    ORAQ-29283 : invalid file operation
    Cause: An attempt was made to read from a file or directory that does not exist, or file or directory access was denied by the operating system.
    and resolved that issue first.
    What was the result of fixing the invalid file access issue? Or what have you attempted so far in resolving that issue?

  • How to  read from excel file and write it using implicit jsp out object

    our code is as below:Please give us proper solution.
    we are reading from Excel file and writing in dynamicaly generated Excel file.it is writing but not as original excel sheet.we are using response.setContentType and response.setHeader for generating pop up for saveing the original file in to dynamically generated Excel file.
    <%@ page contentType="application/vnd.ms-excel" %>
    <%     
         //String dLoadFile = (String)request.getParameter("jspname1");
         String dLoadFile = "c:/purge_trns_nav.xls" ;
         File f = new File(dLoadFile);
         //set the content type(can be excel/word/powerpoint etc..)
         response.setContentType ("application/msexcel");
         //get the file name
         String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
         //set the header and also the Name by which user will be prompted to save
         response.setHeader ("Content-Disposition", "attachment;     filename="+name);
         //OPen an input stream to the file and post the file contents thru the
         //servlet output stream to the client m/c
              FileInputStream in = new FileInputStream(f);
              //ServletOutputStream outs = response.getOutputStream();
              int bit = 10;
              int i = 0;
              try {
                        while (bit >= 0) {
                        bit = in.read();
                        out.write(bit) ;
    } catch (IOException ioe) { ioe.printStackTrace(System.out); }
              out.flush();
    out.close();
    in.close();     
    %>

    If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    class Kopy {
         * @param args [0] = source filename
         *        args [1] = destination filename
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                System.err.println ("Syntax: java -cp . Kopy source destination");
                System.exit(1);
            File in = new File(args[0]);
            long fileLength = in.length();
            long t = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream (in);
            FileOutputStream fos = new FileOutputStream (args[1]);
            FileChannel fci = fis.getChannel();
            FileChannel fco = fos.getChannel();
            fco.transferFrom(fci, 0, fileLength);
            fis.close();
            fos.close();
            t = System.currentTimeMillis() - t;
            NumberFormat nf = new DecimalFormat("#,##0.00");
            System.out.print (nf.format(fileLength/1024.0) + "kB copied");
            if (t > 0) {
                System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
    }

  • How to read from a file

    hello friends i m a newbie in java n as i m self studying java, i got stuck on the input streams.sir could u please help me how to read a file named test.txt from following code.
    import java.io.*;
    class ShowFile {
    public static void main(String args[])
    throws IOException
    int i;
    FileInputStream fin;
    try {
    fin = new FileInputStream(args[0]);
    } catch(FileNotFoundException exc) {
    System.out.println("File Not Found");
    return;
    } catch(ArrayIndexOutOfBoundsException exc) {
    System.out.println("Usage: ShowFile File");
    return;
    // read bytes until EOF is encountered
    do {
    i = fin.read();
    if(i != -1) System.out.print((char) i);
    } while(i != -1);
    fin.close();
    }

    sir i heartly appericiate ur quick response the problem in above code is that i have copied the above code from a book which i m reading but it hasn't included any file for reference whch i can test the code upon ie when it is being compiled n runned the no file found error is indicated

  • How to read from txt file that has words in between?

    Hi all,
    I am using Labview 8.2.
    I would like to read from a text file.  I have data (after each time it is has averaged over 100 waveforms) repeatedly stored on to the file.  The idea is to further improve SNR in post processing by again averaging the data (that has been averaged over the 100 waveforms).  
    I can get LabView  to save the data repeatedly into the file, so it keeps getting appended.
    The problem is to read the data in labview so I can now again average it.  The problem is the labview seperates the sets of data with the following:
    " Channels    1    
    Samples    9925    
    Date    2008/10/28    
    Time    17:16:11.638363    
    X_Dimension    Time    
    X0    -3.0125000000000013E-3    
    Delta_X    2.500000E-6    
    ***End_of_Header***        "
    So When I read it, it only sees the first set of data.
    Can someone please tell me how to read all the sets of data in labview?
    I have attached the file I want to read "acquiredwaveform.txt"  and the basic VI (really basic btw) to read the file.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    ReadFileAndAverage.vi ‏48 KB
    acquiredWaveform.txt ‏605 KB

    Thanks again DFGray for the comments. 
    After the correlations to find the peak positions, i just take the max value.  And you are right the accuracy is limited by the number of  samples per cycle.  Perhaps it would be clearer if you see the code.
    1) Basically I get a signal on the up and downslope of the sine wave.  On the down slope however the signal is negative, i.e. its is flipped.  So before I shift and average...I 'cut' the waveform into 4 (when cycles per buffer = 2, then I get 4 signals, 2 on the up slope and 2 on down slope) bits.  Counting from one, I flip the even number, cut it, and but an array of waveforms which is then sent to be convolved and shifted.
    2) Array of waveforms are stored to be phased shifted (Convolve and shift vi) and averaged (entire averaging vi which uses the convolve and shift vi as a sub vi). 
    * Phase shifting doesn't work when I cut and put it together (So something is wrong in cut waveform vi) 
    * Also if it isn't too time consuming could you give me an example of interpolating and shifting thing.
    * Also if you have any comments regarding the following VIs please let me know.  
    Thanks 
    Attached is:
    1) Cut waveform vi
    2) Convolve and shift
    3) Entire averaging 
    Attachments:
    SubVICutWaveforms.vi ‏37 KB
    SubVIConvolveShift.vi ‏30 KB
    SubVIEntireAveraging2.vi ‏43 KB

  • How to read a properties file

    hi
    I have a properties file.
    I am using load method to load the properties file but i have encountered a problem here.
    the properties file has space like
    FIRST PROP=xyz
    SECOND PROP=abc
    my question is how to read the file
    thank u

    Either format it properly--I think a \ before the space will work--or write your own method to use in place of Properties.load.
    (Or, I suppose, you could inject your own InputStram that translates the lines on the fly to include the \, but that would probably be more trouble than it's worth.)

  • How to Read from two file and write to another file --Please help !!

    Hi all,
    Please suggest me where i'm goin goin wrng.
    I have 2 flat files. one of them is the main file(Ann.dat) has a about 150,000 lines (each line has unique ID from 00001 to 45000) of data and the the other(Miss.dat) has a just a list of IDs that are no longer in use & have to be deleted from the first file(NewAnn.dat). (Note that Ann.dat is a tab delimitted file and Miss.dat is just a list of all invalid IDs)
    Below is my code. It doesn't do what I'm supposed to. Please suggest me or help me with a code to do it. What I'm trying to do is read each of the lines from the 2 files compare the ID in ann.dat with all the IDs in Miss.dat & if it doesn't match with the ID in Miss.dat write the whole line to NewAnn.dat. And do the rest with all the lines in Ann.dat.
    It could be a real dumb question. since i'm not a software professional, I consider myself to be newbie to programming. I desperately need your help.
    import java.io.*;
    import java.util.*;
    public class anntemp{
         public static void main(String[] args)
              String keyAnn ="";
              String keyMis="";
              String recAnn =null;
              String recMis =null;
              try{               
              FileReader fr=new FileReader("C:\\Tom\\Ann.dat");
              BufferedReader br=new BufferedReader(fr);
              int couter=0;
              while ((recAnn = br.readLine())!=null)
                   couter++;
                   keyAnn = recAnn.substring(0, recAnn.indexOf("\t"));
              FileReader fr1=new FileReader("C:\\Tom\\Miss.dat");
              BufferedReader br1=new BufferedReader(fr1);
              while((recMis = br1.readLine())!=null){
              keyMis = recMis.substring(0, recMis.indexOf("\t"));
                   if(keyAnn.equals(keyMis)){
         FileWriter fw=new FileWriter("C:\\Tom\\NewAnn.dat",true);
         BufferedWriter bw=new BufferedWriter(fw);
         PrintWriter pw=new PrintWriter(bw);
         StringBuffer writeValue = new StringBuffer();
         writeValue.append(recAnn);
                                                 pw.println(writeValue.toString());
         pw.flush();
              }catch (Exception expe){
                   System.out.println("In Exception ");
                   expe.printStackTrace();
    Thank you all in advance,
    br

    I think you need to close the files when you are done in the inner loop. Plus I think you'll be overwritting the file in the inner loop if more than one match. It might be easier to read the unused id file into a map at the start, and then loop up the id's from the master file in the map. You can put the unused id's in as the keys, and a Boolean.TRUE as the value (value won't matter). Then just check if the map contains the key for the id read from the master file. That should cut down on disk activity. This assumes the unused id file is smallish.

  • How to read from pdf file using VB

    I have a PDF file which contains three columns, emp no, designation, contact_info. I have 10 rows in that pdf file. I want to read row by row from the pdf file and write into another text file(tab delimited) using VB.
    Could you please help me reading the pdf file?
    Thanks,
    Arindam

    Without reading it in detail, this seems to be automating a save as text function in Acrobat. This will not give you any position information.
    If you want position information without writing a plug-in, you need to use the getPageNthWord and getPageNthWordQuads methods in JavaScript.
    If you have not already done so, you will need to download the Acrobat SDK which has the documentation you need.
    Writing in C# makes even very simple things complicated; if you have a choice, consider VB.

  • How to read from input file and pass to script

     How can I get rid of the hard coded PATH statement and feed script based upon text file input.
       Input is contained in a file..
    'C:\cntprocess\   called sistemfolder.txt that has 2 fields folder
    then shortname.
    example:
     C:\cntprocess\REW1___1~Rew1
     C:\cntprocess\REW2___1~Rew2
     I want the first part in each record passed to script for processing
    C:\cntprocess\REW1___1
    C:\cntprocess\REW2___1
    Pass those values to this Script: I want values from above passed to the $Path
    $path='C:\Sistemi\'
    get-childitem -path $path *.spx | % {
    " Starting File Process....." >> $path\sistem.log
    $PDate = get-date
    $date = get-date -uformat "_%d_%m_%Y_%H%M%S.bak"
    #"Set backup date to $date" >> $path\sistem.log
    $newname=($_.fullname -replace ".spx",$date)
    $file = [System.IO.Path]::GetFileNameWithoutExtension($_.fullname)
    "File backup name is $newname" >> $path\sistem.log
    Rename-Item $_.fullname $newname
    "Renamed file to $newname" >> $path\sistem.log
    $lines = get-content $newname
    foreach ($line in $lines)
    $line + " " + [System.IO.Path]::GetFileNameWithoutExtension($_.fullname) | Out-File "$path\sistem.csv" -append
    Write-Host $_.fullname
    "Files Processed on $PDate are $newname " >> $path\sistem.log
    Thanks.

    OK, I was mistaken a bit on what I originally told you. After you run the command of
    $myFile = Import-Csv -Delimiter '~' -Path $path -Header Path, ShortName
    $myFile is actually an array of PSCustomObjects, so you cannot access it like $myFile.Path, you will actually have to loop through the $myFile first, so try changing your script to be the following and see if that helps any
    param
    [string]$path
    $myFiles = Import-Csv -Delimiter '~' -Path $path -Header Path, ShortName
    # Then you can call it like so
    $myFiles.Path #Returns just the path
    $myFiles.ShortName # Returns the shortname
    $path='C:\AreaSistemi1\'
    foreach ($myFile in $myFiles)
    get-childitem -path $myFile.Path *.spx | % {
    " Starting File Process....." >> $myFile.Pathsistem.log
    $PDate = get-date
    $date = get-date -uformat "_%d_%m_%Y_%H%M%S.bak"
    #"Set backup date to $date" >> $path\sistem.log
    $newname=($_.fullname -replace ".spx",$date)
    $file = [System.IO.Path]::GetFileNameWithoutExtension($_.fullname)
    "File backup name is $newname" >> $myFile.Pathsistem.log
    Rename-Item $_.fullname $newname
    "Renamed file to $newname" >> $myFile.Pathsistem.log
    $lines = get-content $newname
    foreach ($line in $lines)
    $line + " " + $myFile.ShortName | Out-File "$path\sistem.csv" -append
    Write-Host $_.fullname
    "Files Processed on $PDate are $newname " >> $path\sistem.log
    Also looking at your script, you said your text file contained the format of <filePath>~<shortname> but I see you doing a $myFile.Pathisstem.log, where does the Pathisstem.log come from?
    If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.
    Don't Retire Technet

  • How to read from one file and write into another file?

    Hi,
    I am trying to read a File and write into another file.This is the code that i am using.But what happens is last line is only getting written..How to resolve this.the code is as follows,
    public String get() {
         FileReader fr;
         try {
              fr = new FileReader(f);
              String str;
              BufferedReader br = new BufferedReader(fr);
              try {
                   while((str= br.readLine())!=null){
                   generate=str;     
              } catch (IOException e1) {
                   e1.printStackTrace();
              } }catch (FileNotFoundException e) {
                   e.printStackTrace();
         return generate;
    where generate is a string declared globally.
    how to go about it?
    Thanks for your reply in advance

    If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    class Kopy {
         * @param args [0] = source filename
         *        args [1] = destination filename
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                System.err.println ("Syntax: java -cp . Kopy source destination");
                System.exit(1);
            File in = new File(args[0]);
            long fileLength = in.length();
            long t = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream (in);
            FileOutputStream fos = new FileOutputStream (args[1]);
            FileChannel fci = fis.getChannel();
            FileChannel fco = fos.getChannel();
            fco.transferFrom(fci, 0, fileLength);
            fis.close();
            fos.close();
            t = System.currentTimeMillis() - t;
            NumberFormat nf = new DecimalFormat("#,##0.00");
            System.out.print (nf.format(fileLength/1024.0) + "kB copied");
            if (t > 0) {
                System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
    }

  • How to read from pdf file?

    I am new to reading pdf using C# where I have below function in my project. How to recognize text position in pdf file?
    Here _dblRect has 151.0, 696.0, 400.0, 500.0
    _strFileName is txt file name.
    Can someone explain how this function works?
    private string fcnTextFromCrop(string _strFileName, double[] _dblRect, CAcroPDDoc _docOriginal, int _intPage)
                string str = "";
                try
                    object jSObject = _docOriginal.GetJSObject();
                    System.Type type = jSObject.GetType();
                    object target = null;
                    object[] args = new object[] { _intPage };
                    target = type.InvokeMember("extractPages", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, jSObject, args);
                    object[] objArray2 = new object[] { "Crop", 0, 0, _dblRect };
                    type.InvokeMember("setPageBoxes", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, target, objArray2);
                    object[] objArray3 = new object[] { _strFileName, "com.adobe.acrobat.plain-text" };
                    type.InvokeMember("saveAs", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, target, objArray3);
                    object[] objArray4 = new object[] { true };
                    type.InvokeMember("closeDoc", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, target, objArray4);
                    using (StreamReader reader = new StreamReader(_strFileName))
                        str = reader.ReadToEnd();
                        reader.Close();
                    System.IO.File.Delete(_strFileName);
                catch
                    str = "";
                return str;

    Without reading it in detail, this seems to be automating a save as text function in Acrobat. This will not give you any position information.
    If you want position information without writing a plug-in, you need to use the getPageNthWord and getPageNthWordQuads methods in JavaScript.
    If you have not already done so, you will need to download the Acrobat SDK which has the documentation you need.
    Writing in C# makes even very simple things complicated; if you have a choice, consider VB.

Maybe you are looking for

  • External Monitor refresh rate conflict

    I've got the PB 12" and for a longtime have been using a 17" Soyo monitor with the computer closed and Bluetooth devices. It's a great setup. Now one time disconnected it to take the powerbook, and now I can't run it with just the 17" monitor. I don'

  • Importing from I-photo

    Simple question, or at least I hope the answer is simple! I have a folder of pictures in I-Photo and would like to bring the folder into my FCE project. I tried sliding the folder, but it just slides back. Is importing the answer? I have tried that u

  • I pad user from Sri lanka

    Hi , I am Ipad user from Sri lanka. I can't buy any book , songs or films using i tunes  .My credit card is from Sri lankan Bank. Is it a problem ? Please help ....

  • Free handwriting recognition: can you do it?

    I am considering for the first time to buy a tablet for work. The most important characteristic is the possibility to take notes like I would write on a piece of paper. It is possible to do it with iPad and how efficient it is in recognizing a free h

  • Way to find personnel Numbers having 3 tier postings

    Hi Everyone I am SAP HCM QA Could you please help me the table where I can find the list of perners which has 3 tier postings irrespective of the payroll area Thanks