Filepath

Hey,
My last problem using a filechooser lead me into a bunch of related trouble. I wrote this demo to ask - just run the proggy and you'll see.
I got a problem concatenating a path to a folder with a filename.
I got a problem putting "/" in the end of a folder path name.
I got a problem with the "folders only" option for the JFileChooser on Linux.
thx, in advance!!!
package filepath;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class PathFrame extends javax.swing.JFrame {
     private JLabel lbPathByTF;
     private JTextField tfPath;
     private JPanel panSetUpFolderPath;
     private JPanel panFiles;
     private JLabel lbFileName2;
     private JLabel lbFileName1;
     private JLabel lbPathByButton;
     private JButton butPath;
     // Filenames
     private String szFileA = "FileA.txt";
     private String szFileB = "FileB.txt";
     private File folder;
     * Auto-generated main method to display this JFrame
     public static void main(String[] args) {
          PathFrame inst = new PathFrame();
          inst.setVisible(true);
     public PathFrame() {
          super();
          init();
      * inits & grafical mess
     private void init(){
          folder = new File("");
          initGUI();
          initAL();
     private void initGUI() {
          try {
               GridBagLayout thisLayout = new GridBagLayout();
               thisLayout.rowWeights = new double[] {0.0,0.0,0.1,0.0,0.0};
               thisLayout.rowHeights = new int[] {7,7,20,20,7};
               thisLayout.columnWeights = new double[] {0.0,0.1,0.0};
               thisLayout.columnWidths = new int[] {7,7,7};
               getContentPane().setLayout(thisLayout);
               setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
               this.setResizable(false);
                    panFiles = new JPanel();
                    GridBagLayout panFilesLayout = new GridBagLayout();
                    panFilesLayout.rowWeights = new double[] {0.1,0.0,0.1};
                    panFilesLayout.rowHeights = new int[] {7,7,7};
                    panFilesLayout.columnWeights = new double[] {0.1};
                    panFilesLayout.columnWidths = new int[] {7};
                    panFiles.setLayout(panFilesLayout);
                    getContentPane().add(panFiles, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                    panFiles.setBorder(BorderFactory.createTitledBorder("  resulting file paths are now:  "));
                         lbFileName1 = new JLabel();
                         panFiles.add(lbFileName1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                         lbFileName1.setText("my file A");
                         lbFileName1.setPreferredSize(new java.awt.Dimension(350, 22));
                         lbFileName2 = new JLabel();
                         panFiles.add(lbFileName2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                         lbFileName2.setText("my file B");
                         lbFileName2.setPreferredSize(new java.awt.Dimension(350, 22));
                    panSetUpFolderPath = new JPanel();
                    GridBagLayout panSetUpFolderPathLayout = new GridBagLayout();
                    panSetUpFolderPathLayout.rowWeights = new double[] {0.1,0.0,0.0,0.1,0.1};
                    panSetUpFolderPathLayout.rowHeights = new int[] {7,7,7,7,20};
                    panSetUpFolderPathLayout.columnWeights = new double[] {0.0,0.1};
                    panSetUpFolderPathLayout.columnWidths = new int[] {7,7};
                    panSetUpFolderPath.setLayout(panSetUpFolderPathLayout);
                    getContentPane().add(panSetUpFolderPath, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                    panSetUpFolderPath.setBorder(BorderFactory.createTitledBorder("  Set up the path to to a folder:  "));
                         tfPath = new JTextField();
                         panSetUpFolderPath.add(tfPath, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                         tfPath.setText("my path");
                         tfPath.setPreferredSize(new java.awt.Dimension(350, 22));
                         butPath = new JButton();
                         panSetUpFolderPath.add(butPath, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                         butPath.setText("browse");
                         butPath.setPreferredSize(new java.awt.Dimension(100, 22));
                         lbPathByTF = new JLabel();
                         panSetUpFolderPath.add(lbPathByTF, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                         lbPathByTF.setText("my path");
                         lbPathByTF.setPreferredSize(new java.awt.Dimension(350, 22));
                         lbPathByButton = new JLabel();
                         panSetUpFolderPath.add(lbPathByButton, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                         lbPathByButton.setText("my path");
                         lbPathByButton.setPreferredSize(new java.awt.Dimension(350, 22));
               pack();
               setSize(400, 300);
          } catch (Exception e) {
               e.printStackTrace();
     private void initAL(){
          butPath.addActionListener( new ActionListener(){
               public void actionPerformed( ActionEvent ae){
                    choose();
          tfPath.addActionListener( new ActionListener(){
               public void actionPerformed( ActionEvent ae){
                    getPath();
      * actions
      * implements a filechooser to find the folder
     private void choose(){
          JFileChooser fc;
         fc = new JFileChooser(folder.getAbsoluteFile());
          int hInput = fc.showOpenDialog(this);
          if( hInput == JFileChooser.APPROVE_OPTION){
               fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
//               fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                * Problem: selecting folders doesn't work!
                * If I select a folder and click on the open button of the
                * filechooser it just opens but not selected!?
               if(fc.getSelectedFile().exists()){
                    folder = fc.getSelectedFile();
               }else{
                    folder = new File("");
          lbPathByButton.setText( folder.getAbsolutePath());
          refreshFilePaths();
      * takes the path to a folder directly from the <CODE>JTextField</CODE>
     private void getPath(){
          folder = new File(tfPath.getText());
           * Problem: I always obtain the path without "/" or "\" at the end. Thus concatenating
           *           this path with some file name will lead to something odd.
           *           e.g. /mnt/datasettings.xml and not /mnt/data/settings.xml like it should.
           * Problem: Even if I add a "/" in the textfield it just won't take it? It takes "\" but no "/"
           *           at the End. (I'm working on Debian/Linux hence I need "/").
          lbPathByTF.setText( folder.getAbsolutePath());
          refreshFilePaths();
      * basic access
     private void refreshFilePaths(){
          lbFileName1.setText( folder.getAbsolutePath() + szFileA);
          lbFileName2.setText(folder.getAbsolutePath() + szFileB);
}

1)
these
private String szFileA = "FileA.txt";
private String szFileB = "FileB.txt";
should be
private String szFileA = "\\FileA.txt";
private String szFileB = "\\FileB.txt";
2)
you're setting the selection mode after the chooser is visible
fc = new JFileChooser(folder.getAbsoluteFile());
int hInput = fc.showOpenDialog(this);
if( hInput == JFileChooser.APPROVE_OPTION){
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );//fc is already showing???
should be
fc = new JFileChooser(folder.getAbsoluteFile());
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );//<-----move to here
int hInput = fc.showOpenDialog(this);
if( hInput == JFileChooser.APPROVE_OPTION){
//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );//<----moved

Similar Messages

  • Assigning a java value(filepath) to a javascript variable

    I have a JSP where I have a java variable(obtained from session) which is nothing but a filepath(say C:\superb.xpdl). When I try to use the variable in javascript using var scriptVar = "<%= sessionVar %>";, the sessionVar value i.e. the filepath is getting modified (like C:superb.xpdl). Slashes are interpredted in a different way(\t for tab, \n for new line etc.,) How to get the filepath with no modifications while assigning to javascript variable? will encoding(using escape()) and decoding help?

    unfortunately you need to double up the slashes
    maybe this will work
    scriptVar = "<%= sessionVar.replaceAll("\\", "\\\\") %>";
    or maybe it will cause a infinite recursion problem (i'm too lazy to try it)

  • Unable get complete filepath from jsp page using request.getParameter()

    Hey all,
    i am actually trying to get the selected file path value using request.getParameter into the servlet where i will read the (csv or txt) file but i dont get the full path but only the file name(test.txt) not the complete path(C:\\Temp\\test.txt) i selected in JSP page using browse file.
    Output :
    FILE NAME : TEST
    FILE PATH : test.txt
    Error : java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileReader.<init>(FileReader.java:55)
    at com.test.TestServlet.processRequest(TestServlet.java:39)
    at com.test.TestServlet.doPost(TestServlet.java:75)
    JSP CODE:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>DEMO SERVLET</title>
    </script>
    </head>
    <body>
    <h2>Hello World!</h2>
    <form name="myform" action="TestServlet" method="POST"
    FILE NAME : <input type="text" name="filename" value="" size="25" /><br><br>
    FILE SELECT : <input type="file" name="myfile" value="" width="25" /><br><br>
    <input type="submit" value="Submit" name="submit" />
    </form>
    </body>
    </html>
    Servlet Code :
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, FileNotFoundException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
    String filename = request.getParameter("filename");
    out.println(filename);
    String filepath = request.getParameter("myfile");
    out.println(filepath);
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    if (filepath != null) {
    File f = new File(filepath);
    BufferedReader br = new BufferedReader(new FileReader(f));
    String strLine;
    String[] tokens;
    while ((strLine = br.readLine()) != null) {
    tokens = strLine.split(",");
    for (int i = 0; i < tokens.length; i++) {
    out.println("<h1>Servlet TestServlet at " + tokens[i] + "</h1>");
    out.println("----------------");
    out.println("</body>");
    out.println("</html>");
    } finally {
    out.close();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    Needed Output :
    FILE NAME : TEST
    FILE PATH : C:\\Temp\\test.txt
    Any suggestions Plz??

    As the [HTML specification|http://www.w3.org/TR/html401/interact/forms.html] states, you should be setting the enctype to multipart/form-data to be able to upload files to the server. In the server side, you need to process the multipart/form-data binary stream by parsing the HttpServletRequest#getInputStream(). It is a lot of work to get it to work flawlessly. There are 3rd party API's around which can do that for you, such as [Apache Commons FileUpload|http://commons.apache.org/fileupload] (carefully read the User Guide how to use it).
    You can also consider to use a Filter which makes use of the FileUpload API to preprocess the request so that you can continue writing the servlet code as usual. Here is an example: [http://balusc.blogspot.com/2007/11/multipartfilter.html].

  • How to retrieve various file names from a filepath of application server

    Hi All,
    I am using a FILEPATH  of application server which can have multiple file names i want to retrieve data from all the existing files.
    i am using FM "GET_NAME_FILE" but it is applicable only for file name.
    so my question is how to fetch various file names of particular filepath.
    Thanks in advance.

    Hello Mayank,
    You can use the below FM and code
    PARAMETERS: p_file TYPE rlgrap-filename.
    ***AT Selection-Screen*******
    AT SELECTION-SCREEN ON  VALUE-REQUEST FOR p_file.
    ***Function  module for F4 help from Application  server
      CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE'
    * EXPORTING
    *   DIRECTORY              = ' '
    *   FILEMASK               = ' '
       IMPORTING
       serverfile             =  p_file
       EXCEPTIONS
       canceled_by_user       = 1
       OTHERS                 = 2
      IF sy-subrc = 0.
        MESSAGE 'Successful'  type 'I'.
      ENDIF.
    Regards,
    Mithun Shetty

  • Can I define the filepath in "TDMS Open" through a dialog box instead of an explicit definition?

    I'm trying to access a TDMS datafile with "TDMS Open", but I can't ensure that it will always be in the same place.  I've got code that does what I want with the datafile, but I'd really like a dialog box that will generate the filepath.  I'd like to be able to navigate to where the file is, and when selected, define the filepath.
    I've seen this in other vis (if the filepath is left blank, it asks you for the file), but not here. Any thoughts on how to replicate it here?
    Solved!
    Go to Solution.

    File Dialog Express VI in the File I/O >> Advanced Files palette.

  • CFpdf and CFcontent shows filepath and filename in browser

    Thanks to all for past help on my CF questions...
    I've developed an upload application for (logged in to secure environment) users that uploads a pdf outside of the root, moves and renames the file and then cfpdf protects the file with a password. Part of the upload process inserts variables in a SQL database such as Catagory, Subcatagory, FileName, etc. The cffile move puts the file inside the root where I have a security framework. No problem with this.
    I have a cfm page populated (dynamically) with links to the pdf files. These links contain url handlers that pass the filepath and filename. When a user clicks a link, he is carried to an index.cfm that has the security framework and within this page I have cfpdf link to the pdf file (and sets a password) and cfcontent loading the pdf file in the browser. All of this works just fine, as it should.
    However... Because cfpdf sets the filepath/filename source and destination and passes this on to the cfcontent tag -- the filepath and filename are shown in the browser address bar as well as naming the download file the same as the http address (albeit with underscores) if the user saves the file. Anyone with any savvy can figure out the actual filepath and filename and go directly to the file in their browser. They'd still have to type in a password to view the file but I'd rather not have this filepath exposed like this.
    Without having to create a copy of the original and rename the file, is there a way to change what is shown in the browser address and in the download filename? At some point there may be many pdf files uploaded and stored on this site. I'd rather not have 2 copies of each file on the server - the original and one renamed...
    I've googled and googled and can't find an answer anywhere on this. Thanks to anyone pointing me in the right direction here.
    - e

    Finally figured this out...
    Since the file exists on the server, there's no need to use cfpdf and cfcontent to serve up the PDF.
    When the PDF link is clicked, the user is directed to a page that has the security framework where there is a redirect to the PDF on the server. I have the PDF password protected. The PDF opens in the browser and, if saved, is saved with the file name only instead of the whole url+filename.
    Learning to work with CF and PDFs through cfdocument and cfpdf lately has been somewhat frustratingly fun.(!) I guess it was overkill in trying to do the above when all I needed was a direct link to the file itself.
    Hope this will help someone else...
    - e

  • Pulling filepath info from range of pdf's in folder, inserting into excel (VBScript)

    I can code getting page numbers and placing into an excel spreadsheet.  However I need a dialog to pop up asking for a folder path, then the code should count the number of pdf's in the folder and write the folder path to the first cell, number of .pdf's in the folder to the second cell, and then do a page count on each .pdf in the folder and writing them to each of the next cells.
    Note: I need to do this in VBScript, not JS.
    I know I can do this with a simple set of for...next loops and whatever the syntax is for pulling the pdf count in the folder and the file path info.  If someone could post a good vbscript reference for acrobat that would be all I'd need to get this done.  Or any syntax regarding ripping the filepath info and the count of a specific filetype in a folder would also help.
    The dialog box to ask the user to specify a folder will be the most difficult for me as I've never done this before, I know I can use an inputbox but I really need the user to have a folder view for this.

    "BrowseForFolder" is what your are looking for.
    Google will give you examples on mass.
    HTH. Reinhard

  • HI plese Help me out - get filename from filepath

    Hi
     C:\users\satish\desktop\inflow\documentation.txt
    I have a requirement to get file names like
    documentation
    satish reddy

    Hi Satish,
    If you use SSIS 2012, you can also use the Token and TokenCount function to achieve your goal, the expression is as follows:
    Token(Token( @[User::FilePath], "\\",TokenCount( @[User::FilePath] ,"\\")),".",1)
    or
    Replace(Token( @[User::Variable], "\\",TokenCount( @[User::Variable] ,"\\")),".txt","")
    Reference:
    http://technet.microsoft.com/en-us/library/hh213216.aspx
    Regards,
    Mike Yin
    TechNet Community Support

  • How can I read file from filepath and Insert in to SQL Server ?

    Hi,
    I have table called "table1" and has data like this ..
    id
    Folder
    FileName
    1
       f:\cfs\O\
    ENDTINS5090.tif

    D:\Grant\
    CLMDOC.doc
    3
     f:\cfs\Team\
    CORRES_3526.msg
    4
      f:\cfs\S\
    OTH_001.PDF
    I have another table called "table2" with content column is image datatype.
    Id
    FileName
    Content
    1
    FileName
    2
    ENDTINS5090.tif
    3
    CLMDOC.doc
    4
    CORRES_3526.msg
    5
    OTH_001.PDF
    I would like to insert in to content column in the table2 by reading the file from filepath( table1).
    Is there any simple way or SSIS  able to do it ?
    Please help me on this.
    Thank you.

    http://dimantdatabasesolutions.blogspot.co.il/2009/05/how-to-uploadmodify-more-than-one-blob.html
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • What is the correct format of filepath string on Mac os x?

    I am trying to retrieve a file from Mac os x by:
    File file=new File(filepath);
    My boot volume name is "myVol", and filepath is "/myVol/opt/ab.txt". However, when I provide this path, the file is not found. I just figured out that if I use "/opt/ab.txt" the correct file can be found!!
    Now, if I have a shared volume on my machine(I got it by menu "Go-->Connect to Server..."), whose name is "Mac Share", the filepath should be something "/Mac Share/test/123.txt". File file=new File("/Mac Share/test/123.txt") can not find the file. It looks like that it's trying to find 123.txt from /myVol/Mac Share/test directory, which doesn't exist. I even tried "//MacShare/test/123.txt", "Mac Share/test/123.txt", etc., and none of them worked!!
    If you know the correct format to specify the filepath on Mac OS x, please give me help!!!!
    Thanks in advance.

    I don't know the exact answer to your question, but you can probably figure it out on your own like:
    1) Create a File object that represents an existing file. Play around with the path until the file can be found.
    2) Now that you have a File object representing a valid, existing path, use MyFile.getAbsolutePath() to see what the full path string is. MyFile.getCanonicalPath() might provide some answers as well.
    Whatever getAbsolutePath() returns is the correct format for the file path string.

  • PdDoc.open(filePath) gives me an error message.

    Hello,
    I am using pdDoc.Open(filePath) in my application. Its working fine with Acrobat 8.0 in both Windows XP and Vista. But with Acrobat 9.0 in Windows Vista, I am getting the following error message. "There was an error opening the document. The file cannot be found".
    After clicking OK I am able to continue my work. Please help me to solve this issue and thanks in advance for your help.
    Thanks Mohd Mustafa SK

    Hello, sarahehines. 
    Thank you for visiting Apple Support Communities.
    Here are the steps I would recommend going through as they should resolve the issue.
    iTunes 11.1.4 for Windows: Unable to install or open
    http://support.apple.com/kb/TS5376
    Cheers,
    Jason H.

  • Image filepath displays in PDF

    Hi,
    I have converted a WebHelp document -> Word 2007 , applied some formatting/styles, then converted it to PDF. I converted the Word doc by using the "Create PDF -> From File" option in Acrobat Professional  8.2.3
    When the mouse hovers over ALL images in the PDF file, the filepath displays.  I don't want this. Actually, I don't want anythinig to display!  It's interesting to note the the filepath points to the temp directory created (!doc_tmp_folder_0) on my local machine (so it also displays, C:\Documents and Settings\<myname>\My Documents\...\!SSL!\etc). And this temp directory does not exist anywhere on my machine.
    I looked around for some kind of Image setting, both in Word and Acrobat, but I couldn't find anything that I thought resolved this issue.
    Thanks!

    HELP!
    This question is still unanswered and I can't find a good solution.  Surely, I'm not the only one who generates a PDF using RH8 -> Word -> PDF...
    But am I the only one with this image filepath problem?
    Hovering the mouse over an image in the PDF file (generated as above) causes the filepath to display as a tooltip.  This filepath doesn't exist and references a temp folder plus some personally identifying information.
    I can not remove or hide this information unless I create the PDF from Word using Print -> PDF and in this case, all bookmarks/internal links are disabled!  This is becoming a problem as the file is 500 pages (well, 499 to be specific) and I don't have the time to relink my entire document.
    Does anyone else have this problem? If not, how are you generating the PDF, I have tried every way and toggled every option I can think of....

  • Can't create URI from filepath string

    I am trying to open a file (c:\test.txt) from a java application in the default browser. To do this I must specify the filepath as an URI to desktop.browse():
        Desktop desktop;
        if (Desktop.isDesktopSupported()) {
          desktop = Desktop.getDesktop();     
          String test = "c:" + File.separator + "bob.txt";
          System.out.println(test);
          URI pathTofile;
          try {
            pathTofile = new URI(test);
            desktop.browse(pathTofile);
            System.out.println("where is the browser??");
          } catch (URISyntaxException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
        }  But this line:
    pathTofile = new URI(test);
    throws:
    java.net.URISyntaxException: Illegal character in opaque part at index 2: c:\bob.txt
    I have tried replacing backslash with forward slash but that does not help. Any ideas?

    Why not just create a File object from the filepath and then call its toURI method? Then you don't have to assume you actually know how a file URI is constructed and you don't get blindsided by gaps in your knowledge.

  • How can I Locate the correct filepath in a jsp page?

    In http://localhost:8080/myweb/a.jsp, I will call a java bean file which is locate in http://localhost:8080/myweb/WEB-INF/classes/haha/DBConnection.class. This java file requires to read an external file which locates in http://localhost:8080/myweb/WEB-INF/classes/haha/db.txt
    My question is how can I get the correct filepath in this environment?
    inputStream = new BufferedReader(new FileReader(????????));
    Only this will work
    inputStream = new BufferedReader(new FileReader("D:\Program Files\Apache Software Foundation\Tomcat 5.5\db.txt"));
    But no one will place the file here, and it is impossible to do this when upload to 3rd party hosting.
    Any suggestion? thx.

    Thx all, in a jsp page, calling this method is fine.
    ServletContext s = getServletContext();
    String a = s.getRealPath("/");
    In a Servlet file, below method is ready to use:
    String b = getServletConfig().getServletContext().getRealPath("/");
    My problem is, I have a jsp page, which initialize a java bean , this java file is responsible for Database Connection, which will read the external text file to get the login, password and database name. So I won't need to recompile this file every time when I place in different platform with different configuration. I only need to edit the text file is ok.
    But How can I get the absolute file path when that jsp page initialize that java bean file? Below is my error, any suggestions are thx.
    package sql;
    import java.sql.*;
    import java.util.ArrayList;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class DBConnection extends HttpServlet{
    public String sql = null;
    public Connection con = null;
    public Statement statement = null;
    public ResultSet rs = null;
    private BufferedReader inputStream = null;
    private static ArrayList<String> arr = new ArrayList<String>();
      public DBConnection(){
        String fs = System.getProperty("file.separator");
        ServletContext s = getServletContext();
        String realpath = s.getRealPath("/");
        String filepath = realpath + "WEB-INF"+fs+"Properties"+fs+"db.txt";
        try{
          inputStream = new BufferedReader(new FileReader(filepath));
          String l;
          while ((l = inputStream.readLine()) != null) {
            arr.add(l);
          Class.forName("com.mysql.jdbc.Driver");
          this.con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+arr.get(0)+"?user=" +arr.get(1)+ "&password="+arr.get(2)+"&useUnicode=true&characterEncoding=utf-8");
          this.statement = this.con.createStatement();
        }catch (Exception e){
          System.err.println(e.getMessage());
        }finally{
    }java.lang.NullPointerException
         javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
         sql.DBConnection.<init>(DBConnection.java:20)
         html.ShowCategory.<init>(ShowCategory.java:17)
         org.apache.jsp.left_jsp._jspService(left_jsp.java:66)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

  • Getting filename from a string including filepath and filename

    How I can get a filename from a string which includes both
    filepath and filename? The filepath is not always the same. For
    example, the variable could include a "C:\temp\test.doc" or
    "C:\files\docfiles\test.doc" and I need to get the filename
    "test.doc" and save it to another variable. Thanks in
    advance.

    on getFilenameFromPath vPath
    oldDelim=the itemDelimiter
    the itemDelimiter=the last char of the moviePath
    iFilename=the last item of vPath
    the itemDelimiter=oldDelim
    return iFilename
    end
    Put that into a movie script. Then you can call the function
    any time
    to retrieve the last part of the path- like this:
    put getFilenameFromPath("C:\temp\test.doc")
    -- "test.doc"
    As an added bonus, it is cross-platform so it will work on a
    Mac as well
    as a PC.

  • Lsmw error filepath with F4 help

    Hi,
    I have to download error data from a lsmw. I have to use gui_download at end_of_processing.
    Now I want to know how I can implement the selection screen for the filepath parameter and
    attach the f4 help for it.
    correct answer will be rewarded.
    regards,
    Tanmay

    Hi,
    PARAMETERS : P_FILE1 LIKE RLGRAP-FILENAME.         "Filepath -Pr.Server
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_FILE1.
      PERFORM at_sel_screen USING P_FILE1.
    FORM AT_SEL_SCREEN USING    P_P_FILE1.
    *FM is called to give the F4 help for the selection of file from Local
    *drives
      CALL FUNCTION 'WS_FILENAME_GET'
         EXPORTING
            DEF_FILENAME     = '. '
            DEF_PATH         = 'C:\ '
            MASK             = ',.,..'
            MODE             = '0'
            TITLE            =
         IMPORTING
            FILENAME         = P_FILE1
         EXCEPTIONS
            INV_WINSYS       = 1
            NO_BATCH         = 2
            SELECTION_CANCEL = 3
            SELECTION_ERROR  = 4
            OTHERS           = 5
      IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    ENDFORM.                    " AT_SEL_SCREEN

Maybe you are looking for