Scala/java reading files in a project

Source: Internet
Author: User

First, get the location of the jar Package 1. Using Classpath
String path = This.getclass (). Getprotectiondomain (). Getcodesource (). GetLocation (). GetPath ();

The return value is/xxx/xxx.jar this form. If the path contains Unicode characters, you also need to transcode the path

Path = Java.net.URLDecoder.decode (path, "UTF-8");
2. Using the Java runtime's system properties to get the jar file location is also/xxx/xxx.jar this form
String Path = System.getproperty ("Java.class.path"); int firstindex = Path.lastindexof (System.getproperty ("Path.separator")) + 1; int lastIndex = Path.lastindexof (file.separator) + 1; Path = path.substring (FirstIndex, LastIndex);

Path.separator is obtained under Windows system; (semicolon), under Linux: (colon). That is, the environment variable is commonly used to split the path of two symbols, such as in Windows we often set the environment variable path=xxxx\xxx;xxx\xxx; here is the semicolon.

File.separator is the/(slash) with \ (backslash), Windows is \ (backslash), Linux is/(slash).

Second, read the file in the JAR Package 1. Get the path to the file before loading the file resource
Java.net.URL FileURL = This.getclass (). GetResource ("/ui/image/background.jpg"); Javax.swing.Image backGround = new ImageIcon (FileURL). GetImage ();
2. Load the object directly
InputStream in = This.getclass (). getResourceAsStream ("/ui/image/background.txt");
Third, the JAR package program Operation 1.java
Java  -classpath  f:/testhello.jar  Test2 or JAVA-CP  f:/testhello.jar  Test2
2.scala
Scala  -classpath  F:/testhello.jar  Test2

Scala/java read files in project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.