File and Buffered Streams
作者:互联网
Access Files
- Often use streams for file-based I/O
- Class for each stream type in java.io package
- FileReader
- FileWriter
- FileInputStream
- FileOutputStream
- The java.io classes are now deprecated
- Still widely used in code
Buffered Streams
- Direct file access can be inefficient
- Buffered streams can improve efficiency
- Buffers content in memory
- Peforms reads/writes in large chunks
- Reduces underlying stream interaction
- BufferedReader
- BufferedWriter
- BufferedInputStream
- BufferedOutputStream
try(BufferedReader br = new BufferedReader(new FileReader("file1.txt"))){
int intVal;
while(intVal = br.read()) >= 0){
char charVal = (char) intVal;
// do something with charVal
}
}
extra benefit of buffered streams: break line support
Line breaks vary across platform
- Unix: \n
- Windows: \r\n
Buffered streams add line break support
- Uses correct value for current platform
- Buffered Writer: generate line breaks with newLine()
- Buffered Reader: line based read with readLine()
// 多行读写模板
void writeData(String[] data) throws IOException{
try(BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))){
for(String d: data){
bw.write(d);
bw.newLine();
}
}
}
void readData() throws IOException{
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))){
String inValue;
while((inValue= br.readLine()) != null){
System.out.println(inValue);
}
}
}
标签:Buffered,File,streams,br,new,Streams,line,data 来源: https://blog.csdn.net/jzhong720/article/details/118441793