To enable Web projects to access resources in the referenced Java project, you need to place the files of the required IO operations into the SRC directory in Java projectfa YiIn Java project, classes that have IO operations need to write this
package Cn.edu.test;import Java.io.bufferedreader;import Java.io.file;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;public class Writer {public static void main (string[] args) throws IOException {System.out.println (read ());} public static String read () {///Resource/a/b/test.txt in src directory inputstream r Esourceasstream = Writer.class.getClassLoader (). getResourceAsStream ("Resource/a/b/test.txt"); BufferedReader br = new BufferedReader (new InputStreamReader (Resourceasstream)); String readLine = null; try {readLine = Br.readline (); } catch (IOException e) {e.printstacktrace (); } finally {if (BR! = null) try {br.close (); } catch (IOException e) {e.printstacktrace (); }} System.out.println (ReadLine); return readLine; }}
|
However, this method has some limitations, such as getting the path after the return value is a InputStream input stream object, when we use Apache Commons-io this powerful IO package to manipulate the file, the method in the package receives the parameter is a string type of path Instead of the input stream object. So the method is not easy to useCommons-io Package. Method TwoThe same class in Java project, if there is an IO operation, you need to write this
package Cn.edu.test;import Java.io.file;import Java.io.ioexception;import Org.apache.commons.io.fileutils;public class Writer {public static void main (string[] args) throws IOException {System.out.println (read ());} public static String R EAD () {///resource/a/b/test.txt is stored in the SRC directory under String path = Writer.class.getClassLoader (). GetResource (""). GetPath (); Path + = "Resource/a/b/test.txt"; SYSTEM.OUT.PRINTLN (path); String readfiletostring = null; try {readfiletostring = fileutils.readfiletostring (new File); } catch (IOException e) {e.printstacktrace (); } return readfiletostring; }} |
However, this approach also has some limitations, if you use this method, you need to use the SRC directory in Java project, the resource file is copied to the SRC directory in Web project, However, the return value obtained in this way is a path name of type string, which can then be used with a powerful Commons-io package, such as the Fileutils class .
Java Project Packaging, after publishing to Web project, running Web project appears to be unable to find a solution to the resources in Java project