To work with such data-formatted file content, you could use the DataInputStream class:
Alternatively, you can read a file using the FileReader class, which is altogether very different:
Lots of choices, lots of code. Java SE 7 does much to simplify and unify all of this.
Files, Paths class — new in Java SE 1.7. With it, you can easily create new files, create temporary files, create new (and temporary) directories, copy and move files various different ways, create symbolic links, open existing files, delete files, work with file attributes, read from files, and write to files. Just about everything you've ever wanted to do with a file can now be done through this one class
Want to open an existing file by path? Here it is:
Path path = FileSystems.getDefault().getPath(".", name); // Paths.get("test1");
|
Want to read all of the bytes in that file? No more looping, here it is:
byte[] filearray = Files.readAllBytes(path);
|
Would you rather deal with the file line-by-line? No problem:
List<String> lines = Files.readAllLines(path, Charset.defaultCharset() );
|
Is it a large file that you'd rather use buffered IO with? Here you go:
BufferedReader br=Files.newBufferedReader(path,Charset.defaultCharset());
String line = null;
while ( (line = br.readLine()) != null ) { /* … */ }
|
Surely, it must take more than that to create and write to file, right? Wrong: // create new,overwrite if exists
String content = …
Files.write( path, content.getBytes(),StandardOpenOption.CREATE);
|
You can buffer the output and write all of the bytes with one extra line of code:
BufferedWriter-bw=Files.newBufferedWriter(path,Charset.defaultCharset(),StandardOpenOption.CREATE);
bw.write(content, 0, content.length());
|
the StandardOpenOption class in Java 1.7 contains all of the file and directory attributes you need to deal with file existence create, delete, overwrite, append, and other options. Again, having this all in one helper class helps a great deal.
The old and new File IO APIs can be used together:
Path path = FileSystems.getDefault().getPath(".", name);
InputStream in = Files.newInputStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> lines = new ArrayList<>();
String line = null;
while ((line = reader.readLine()) != null)
lines.add(line);