开发者

Accessing file from package

suppose I put a file a.txt in package com.xyz and t开发者_开发技巧he try access it like following. Will it work?

Hi All,

          import com.xyz.*;
          public class Hello
          { 
            File f = new File("a.txt");
             ...
          }

It is not working for me. Is there any workaround?


Use Class.getResource() or Class.getResourceAsStream(). see for example the Sun demo source at http://jc.unternet.net/src/java/com/sun/WatermarkDemo/WatermarkDemo.java


I will offer the same answer as jcomeau_ictx, but a lot shorter (around 30 lines in one file as opposed to >380 in 1 source file of 5), ..and with a screenshot. ;)

Accessing file from package

import javax.swing.*;
import java.net.URL;

class GetResource {

  GetResource() {
    Class cl = this.getClass();
    final URL url = cl.getResource( cl.getName() + ".java" );
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JEditorPane ep = new JEditorPane();
        try {
          ep.setPage(url);
          JScrollPane sp = new JScrollPane(ep);
          sp.setPreferredSize(new java.awt.Dimension(400,196));
          JOptionPane.showMessageDialog(null, sp);
        } catch(Exception e) {
          e.printStackTrace();
          JOptionPane.showMessageDialog(
            null,
            e.getMessage() + "  See trace for details.");
        }
      }
    });
  }

  public static void main(String[] args) {
    new GetResource();
  }
}


Based on your responses to the comments above. If you are looking for a work around, just specify the path to the .txt file on the file system. Putting it in a package does not help.

new File ("a.txt")

looks for a file on the the file system and not within a package.

Please also read the javadocs on File: http://download.oracle.com/javase/6/docs/api/java/io/File.html

However I do not see the rationale in putting the file inside a package unless you would want to use it as a resource. In which case @jcomeau_ictx has the right solution


It's depend on your class path of java from where you can run this class. If both are in same place then it will work. Then no need to define path in file. But the file was not in the classpath dir then must be define path of that file otherwise file not found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜