Tag: Relative pack red string sha Fread open failed space
Always think that using the new file (relative path) can read the files in the class directory, not actually. Online query Some information, figure out the principle, summarized as follows:
PackageCom.coshaho.learn;ImportJava.io.BufferedReader;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader; Public classfilepathlearn{ Public Static voidMain (string[] args)throwsIOException {//Scenario 1//Get Code Engineering path, production environment only class files, no Java files and code engineering, this way is not advisableFile File =NewFile (""); System.out.println (File.getcanonicalpath ()); //Scenario 2//Get Code Engineering Path, problems with use on production environmentSystem.out.println (System.getproperty ("User.dir")); //Scenario 3//gets the class file root directory (the path contains spaces that are escaped as%20, at which point the new file fails)File =NewFile (Filepathlearn.class. GetResource ("/"). GetPath ()); System.out.println (File.getcanonicalpath ()); //Scenario 4//gets the class file directory (the path contains spaces that are escaped as%20, at which point the new file fails)File =NewFile (Filepathlearn.class. GetResource (""). GetPath ()); System.out.println (File.getcanonicalpath ()); //Scenario 5//As you can see, this method has the same effect as scenario 3File =NewFile (Filepathlearn.class. getClassLoader (). GetResource (""). GetPath ()); System.out.println (File.getcanonicalfile ()); //the new file may fail because the path may contain spaces, so you can open the stream to read the file directlyInputStream stream = Filepathlearn.class. GetResource ("Ce_excel.xml"). OpenStream (); InputStreamReader Reader=NewInputStreamReader (stream); BufferedReader Bufreader=NewBufferedReader (reader); String Str=NULL; while(str = bufreader.readline ())! =NULL) {System.out.println (str); } }}
Java get configuration file and path