Saving/Loading files java [duplicate]
Possible Duplicate:
Java: how to create and write to a file
I am new to java and wanted to know of theres an easy way to save/load a file to/from a desired path. Is there an easy way to do this?
The simplest library to use it likely to be Apache FileUtils
You can load/save a file as a single line.
for(String line: FileUtils.readLines(filename)) {
// process the line.
}
It will take care of exception handling and make sure the file is closed.
Note: this tool works best with file less than 100 MB. If you have really large files, you need to read the contents progressively yourself.
The plain Java runtime does not offer some file copy methods. So if we don't want to use an additional library (like FileUtils, see Peter's answer) or call external programs (like copy.cmd
or cp
), then we have to read all bytes from a file into memory and write them to a new file.
Here's a nice tutorial that shows exactly how to copy from one file to another (although: that code runs much too slow for practical use because it does not buffer the streams)
精彩评论