I really need help on my java project. My problem is that I am new to Java and I can't figure out how to pass a input file in java.
I need to open a .dat file, read the file, and set it as a named constant so I can pass it to other methods as a string.
For example I want to open myFle.dat in my beginning method and pass it to a method like this so I can work with it their
doMethod(fileString);
If possible talk simple java to me because I am new to this.
You need to open a Stream
to the File
and read that into a StringBuilder
, here is a simple example:
final File file = new File("/path/to/my/file.txt");
final StringBuilder stringBuilder = new StringBuilder();
try (final Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
final CharBuffer cb = CharBuffer.allocate(1024);
while (reader.read(cb) != -1) {
stringBuilder.append(cb.flip());
cb.clear();
}
}
final String fileAsString = stringBuilder.toString();
This assumes the file is in "UTF-8" encoding. The code uses the Java 7 try-with-resources construct to close the Reader
when you're done with it. Otherwise you would need to use a try-finally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.