java - Reading file from unknown path -
the following code reads text file specific path.
import java.io.*; public class game { static fileinputstream fin = null; static datainputstream din = null; static bufferedreader br = null; public void run() { fin = new fileinputstream("c:\\users\\user 1\\desktop\\project java\\players.txt"); din = new datainputstream(fin); br = new bufferedreader(new inputstreamreader(din)); ...}
my problem want read players.txt file path, example if run program machine path not same.
create config.properties
file in class path , store path file in variable this
pathtofile = c:\users\user 1\desktop\project java\ nameoffile = players.txt
then, create config
class , read properties file using properties
class supplied oracle. create appropriate setters , getters of aforementioned 2 variables inside config
class , read file this:
import java.io.*; import packagename.config; public class game { static fileinputstream fin = null; static datainputstream din = null; static bufferedreader br = null; static config config = new config(); public void run() { fin = new fileinputstream(config.getpathtofile + config.getfilename); din = new datainputstream(fin); br = new bufferedreader(new inputstreamreader(din)); }
with method, you'll have stored path file externally, every time want run java program machine, you'd have edit config.properties
file , execute jar
console, no code modifications.
note
as "best" practice, avoid including hardcoded paths or names anytime subject change (folder names, db fields etc.). first rule, "gather" these names in central location, in our case class. doing so, every time name changes, have change once instead of searching across entire project.
as second rule, isolate these names code, allow executed without code change inside properties file, regardless of folder structure, os used etc. doing so, not know java or programming @ all, can rename couple of variables in text file , run program.
Comments
Post a Comment