java 文件读写--转载
2015-08-28 16:40
573 查看
读文件
http://www.baeldung.com/java-read-file
Then, we will discuss how to read a UTF-8 encoded file and how to create String from contents of a file.
Finally, we’ll explore the new techniques to read from file in Java 7.
This article is part of the “Java – Back to Basic” series here on Baeldung.
?
The following code reads from the file using BufferedReader:
?
Note that readLine() will return null when the end of the file is reached.
?
We’ll use a simple whitespace as the delimiter:
?
Note that the default delimiter is the whitespace, but multiple delimiters can be used with aScanner.
The way the tokenizer works is – first, we need to figure out what the next token is – String or number; we do that by looking at the tokenizer.ttype field.
Then, we’ll read the actual token based on this type:
tokenizer.nval – if the type was a number
tokenizer.sval – if the type was a String
The file simply contains:
?
The following code reads from the file both the String and the number:
?
Note how the end of file token is used at the end.
Let’s start with the actual file itself:
?
The following test reads the file using a DataInputStream:
?
?
and:
?
Let’s now use a SequenceInputStream to read the two files and merge them into one:
?
The contents of the file:
?
The following code reads data bytes from the file using FileChannel and RandomAccessFile:
?
?
?
The following code append data read from the file into a StringBuilder line by line:
?
10.1. Read a Small File with Java 7
The file contents:
?
The following code shows how to read small file using the new Files class:
?
Note that you can use the readAllBytes() method as well if you need binary data.
10.2. Read a Large File with Java 7
If we want to read a large file with Files class, we can use the BufferedReader.
The file contents:
?
The following code reads the file using the new Files class and BufferedReader:
?
写文件
We’ll also take a look at locking the file while writing and discuss some final take-aways on writing to file.
This article is part of the “Java – Back to Basic” series here on Baeldung.
?
The output in the file will be:
?
We can then append a String to the existing file:
?
The file will then be:
?
?
The resulting file will contain:
?
Note how we’re not only writing a raw String to file, but also some formatted text with theprintf method.
We can create the writer using FileWriter, BufferedWriter or even System.out.
?
The output in the file will of course be:
?
?
RandomAccessFile enable us to write at a specific position in the file given the offset – from the beginning of the file – in bytes. The following code writes an integer value with offset given from the beginning of the file:
?
If we want to read the int stored at specific location, we can use the following method:
?
To test our functions, let’s write an integer – edit it – and, finally, read it back:
?
?
?
?
So, as you can see – it’s just the creation of the temporary file that is interesting and different – after that point, writing to the file is the same.
10. Lock File Before Writing
Finally, when writing to a file, you sometimes need to make extra sure that no one else is writing to that file at the same time. Basically – you need to be able to lock that file while writing.
Let’s make use of the FileChannel to try locking the file before writing to it:
?
Note that if the file is already locked when we try to acquire the lock, anOverlappingFileLockException will be thrown.
If we try to read from a file that doesn’t exist, a FileNotFoundException will be thrown
If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream
Looking at the common usage practices, we can see – for example – that PrintWriter is used to write formatted text; FileOutputStream to write binary data; DataOutputStream to write primitive data types; RandomAccessFile to write to a specific position; FileChannel to write faster in larger files. Some of the APIs of these classes do allow more, but this is a good place to start.
The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.
http://www.baeldung.com/java-read-file
Java – Read from File
1. Overview
In this tutorial we’ll explore different ways to read from a File in Java; we’ll make use ofBufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream andFileChannel.Then, we will discuss how to read a UTF-8 encoded file and how to create String from contents of a file.
Finally, we’ll explore the new techniques to read from file in Java 7.
This article is part of the “Java – Back to Basic” series here on Baeldung.
2. Read with BufferedReader
Let’s start with a simple way to read from file using BufferedReader; the file itself contains:?
?
3. Read with Scanner
Next, let’s use a Scanner to read from the File – the file contains:?
?
4. Read with StreamTokenizer
Next, let’s read a text file into tokens using a StreamTokenizer.The way the tokenizer works is – first, we need to figure out what the next token is – String or number; we do that by looking at the tokenizer.ttype field.
Then, we’ll read the actual token based on this type:
tokenizer.nval – if the type was a number
tokenizer.sval – if the type was a String
The file simply contains:
?
?
5. Read with DataInputStream
We can use DataInputStream to read binary or primitive data type from file.Let’s start with the actual file itself:
?
?
6. Read with SequenceInputStream
Now, let’s look at how to concatenate two input streams into one usingSequenceInputStream; the 2 input files will simply contain:?
?
?
7. Read with FileChannel
If we are reading a large file, FileChannel can be faster than standard IO.The contents of the file:
?
?
8. Read UTF-8 encoded file
Now, let’s see how to read a UTF-8 encoded file using BufferedReader:?
9. Read a file into a String
We can make good use of StringBuilder to read the entire contents of a file into a String. Let’s start with the file:?
?
10. Read from File using Java 7
Java 7 introduces a new way of working with files and the filesystem – let’s make use of that to read files.10.1. Read a Small File with Java 7
The file contents:?
?
10.2. Read a Large File with Java 7
If we want to read a large file with Files class, we can use the BufferedReader.The file contents:
?
?
11. Conclusion
As you can see, there are many possibilities of reading data from a file using plain Java. You can go for BufferedReader to read line by line, Scanner to read using different delimiters, StreamTokenizer to read file into tokens, DataInputStream to read binary data and primitive data types, SequenceInput Stream to link multiple files into one stream,FileChannel to read faster from large files, etc.写文件
Java – Write to File
1. Overview
In this tutorial we’ll explore different ways to write to a file using Java. We’ll make use ofBufferedWriter, PrintWriter, FileOutputStream, DataOutputStream, RandomAccessFile,FileChannel and the Java 7 Files utility class.We’ll also take a look at locking the file while writing and discuss some final take-aways on writing to file.
This article is part of the “Java – Back to Basic” series here on Baeldung.
2. Write with BufferedWriter
Let’s start simple – and use BufferedWriter to write a String to a new file:?
?
?
?
3. Write with PrintWriter
Next – let’s see how we can use a PrintWriter to write formatted text to a file:?
?
We can create the writer using FileWriter, BufferedWriter or even System.out.
4. Write with FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using aFileOutputStream:?
?
5. Write with DataOutputStream
Next – let’s take a look at how we can use a DataOutputStream to write a String to file:?
6. Write with RandomAccessFile
Let’s now illustrate how to write and edit inside an existing file – rather than just writing to a completely new file or appending to an existing one. Simply put – we need random access.RandomAccessFile enable us to write at a specific position in the file given the offset – from the beginning of the file – in bytes. The following code writes an integer value with offset given from the beginning of the file:
?
?
?
7. Write with FileChannel
If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:?
8. Write to file using Java 7
Java 7 introduces a new way of working with the filesystem, along with a new utility class –Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file:?
9. Write to temporary file
Now, let’s try to write to temporary file. The following code creates a temporary file and writes a String to it:?
10. Lock File Before Writing
Finally, when writing to a file, you sometimes need to make extra sure that no one else is writing to that file at the same time. Basically – you need to be able to lock that file while writing.Let’s make use of the FileChannel to try locking the file before writing to it:
?
11. Notes
After exploring so many methods of writing to a file, let’s discuss some important notes:If we try to read from a file that doesn’t exist, a FileNotFoundException will be thrown
If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream
Looking at the common usage practices, we can see – for example – that PrintWriter is used to write formatted text; FileOutputStream to write binary data; DataOutputStream to write primitive data types; RandomAccessFile to write to a specific position; FileChannel to write faster in larger files. Some of the APIs of these classes do allow more, but this is a good place to start.
12. Conclusion
This article illustrates the many options of writing data to a File using Java.The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.
相关文章推荐
- Eclipse 插件Maven在使用 add dependency,找不到包,解决办法
- java给图片添加水印文字
- Java反射机制深入详解
- Eclipse新导入web项目run on server
- 8个超实用的Java测试工具和框架
- Struts 2 - Architecture
- 详解Java解析XML的四种方法
- java的instanceof 运算符
- Struts2中一个自定义拦截器的使用
- JDK7下载地址
- spring 3 mvc hello world + mavern +jetty
- java中使用switch case报错case expressions must be constant expressions
- mac JAVA_HOME
- Struts 2 - Environment Setup
- java IO流api使用详解
- 经典算法之0-1背包问题
- Struts 2 Overview
- Java中keySet()返回值的排序问题
- Struts 2 Tutorial Basic MVC Architecture
- java对象和json对象之间互相转换