자바 학습 노트 의 Buffered Reader 와 Buffered Writer
25012 단어 Java
문자 흐름 읽 기와 쓰기 의 효율 을 높이 기 위해 버퍼 메커니즘 을 도입 하여 문자 대량 읽 기와 쓰 기 를 실시 하여 단일 문자 읽 기와 쓰기 의 효율 을 높 였 다.BufferedReader 는 문자 읽 기 속 도 를 빠르게 하 는 데 사용 되 며,BufferedWriter 는 쓰기 속 도 를 빠르게 하 는 데 사 용 됩 니 다.
2. BufferedWriter
2.1 계승 체계 와 방법
java.lang.Object
----java.io.Writer
------java.io.BufferedWriter
구조 방법
BufferedWriter(Writer out)
Creates a buffered character-output stream that uses a default-sized output buffer.
BufferedWriter(Writer out, int sz)//sz
Creates a new buffered character-output stream that uses an output buffer of the given size
흔 한 방법
void flush()Flushes the stream.//캐 시 영역 새로 고침
void write(String s,int off,int len)Writes a part of a String.//지정 한 문자열,off 오프셋,len 이 들 어 갈 문자열 의 길 이 를 기록 합 니 다2.2 인 스 턴 스 코드
package ReaderWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
* @author pecu
*
*/
public class BufferedWriterReview {
public static void main(String[] args) {
//writeFile1();
writeFile2();
}
private static void writeFile2() {
BufferedWriter bw=null;
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader("fw.txt"));
bw = new BufferedWriter(new FileWriter("bw2.txt"));
String buff=null;
while((buff=br.readLine())!=null){ // ,
// , 0, buff
bw.write(buff, 0,buff.length());
bw.newLine(); //
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void writeFile1() {
BufferedWriter bw=null;
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader("fw.txt"));
bw = new BufferedWriter(new FileWriter("bw.txt"));
char buff[] = new char[1024];
int len;
while((len=br.read(buff))!=-1){ // buff
bw.write(buff, 0, len); // buff 0 len
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bw!=null){
try {
bw.close()`
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3. BufferedReader
3.2 계승 체계 와 방법
1.상속 체계
java.lang.Object
----java.io.Reader
----java.io.BufferedReader
2.구조 방법
1、BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input buffer.
2、BufferedReader(Reader in, int sz)//sz
Creates a buffering character-input stream that uses an input buffer of the specified size.
3.흔 한 방법
3.2 인 스 턴 스 코드
package ReaderWriter;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
*
* @author pecu
*
*/
public class BufferedReaderReview {
public static void main(String[] args) {
readFile();
}
private static void readFile() {
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader("fw.txt");
br = new BufferedReader(fr);
String line=null;
while((line=br.readLine())!=null){// line-termination characters
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4 사용자 정의 Buffered Reader 와 Buffered Writer
사용자 정의 BufferedReader
/**
*
* @author pecu
*
*/
public class CustomBufferedReader extends Reader{
Reader r;
private char[] buff; //
private int lineNumber=0; //
public CustomBufferedReader(Reader r) {
super();
this.r = r;
buff = new char[8192];
}
public int readInt() throws IOException{
return r.read();
}
public String readLine2() throws IOException {
int ch = 0;
StringBuffer sb = new StringBuffer();
synchronized (lock) {
while((ch=readInt()) != -1){
if(ch == '\r'){
continue;
}
if(ch == '
'){
++lineNumber;
return sb.toString();
}
sb.append((char)ch);
}
}
if(sb.length()==0) return null;
++lineNumber;
return sb.toString();
}
public String readLine() throws IOException {
int ch = 0;
int count = 0;
synchronized (lock) {
while((ch=readInt()) != -1){ //
if(ch == '\r'){ // '\r'
continue;
}
if(ch == '
' ){
++lineNumber;
return new String(buff,0,count);
}
buff[count++]= (char) ch;
}
}
if(count==0) return null; //
++lineNumber;
return new String(buff,0,count);
}
public void close() throws IOException {
if (r!=null) {
r.close();
}
}
public int getLineNumber() {
return lineNumber;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
checkBounds(cbuf, off, len);
return r.read(cbuf, off, len);
}
/**
*
*
* @param cbuf
* @param off
* @param len
*/
private void checkBounds(char[] cbuf, int off, int len) {
if (cbuf == null) {
throw new NullPointerException("cbuf is null");
}
if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length)
|| (off + len) < 0 || (off + len) > cbuf.length) {
throw new ArrayIndexOutOfBoundsException();
}
if (0==len) {
return;
}
}
}
사용자 정의 BufferedWriter
/**
* @author pecu
*/
public class CustomBufferedWriter extends Writer {
private static final String LINE_SEPARATOR = System
.getProperty("line.separator");
private Writer writer;
private static final int cacheSize = 8192; //
private char buff[]; //
private int nChars, charIndex; //
public CustomBufferedWriter(Writer writer) {
this(writer, cacheSize);
}
public CustomBufferedWriter(Writer writer, int sz) {
super();
if (sz <= 0) {
throw new IllegalArgumentException("Buffered sz<=0");
}
this.writer = writer;
nChars = sz;
charIndex = 0;
buff = new char[sz];
}
public void newLine() throws IOException {
write(LINE_SEPARATOR);
// write(LINE_SEPARATOR,0,LINE_SEPARATOR.length());
}
public void write(int c) throws IOException {
if (charIndex >= nChars) {
flushBuffer();
}
buff[charIndex++] = (char) c;
}
public void write(String str) throws IOException{
write(str, 0, str.length());
}
@Override
public void write(String str, int off, int len) throws IOException {
securityCheck();
// 1
// char[] charArray = str.toCharArray();
// write(charArray, off, len);
// 2
while (len>0) {
int lenght=Math.min(nChars-charIndex, len);
str.getChars(off, off+lenght, buff, charIndex);
len-=lenght;
charIndex+=lenght;
if (charIndex>=nChars) {
flushBuffer();
}
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
synchronized (lock) {
checkBounds(cbuf, off, len);
if (len>=nChars) {
flushBuffer();
writer.write(cbuf, 0, len);
return;
}
while (len>0) {
int length=Math.min(nChars-charIndex, len);
System.arraycopy(cbuf, off, buff, charIndex, length);
len-=length;
charIndex+=length;
if (charIndex>=nChars) {
flushBuffer();
}
}
}
}
/**
*
*
* @param cbuf
* @param off
* @param len
*/
private void checkBounds(char[] cbuf, int off, int len) {
if (cbuf == null) {
throw new NullPointerException("cbuf is null");
}
if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length)
|| (off + len) < 0 || (off + len) > cbuf.length) {
throw new ArrayIndexOutOfBoundsException();
}
if (0==len) {
return;
}
}
@Override
public void flush() throws IOException {
synchronized (lock) {
securityCheck();
flushBuffer();
writer.flush();
}
}
@Override
public void close() throws IOException {
synchronized (lock) {
securityCheck();
flush();
writer = null;
buff = null;
}
}
/**
*
*
* @throws IOException
*/
public void flushBuffer() throws IOException {
synchronized (lock) {
securityCheck();
if (charIndex == 0)
return;
writer.write(buff, 0, charIndex);
charIndex = 0;
}
}
/**
*
*
* @throws IOException
*/
public void securityCheck() throws IOException {
if (writer == null) {
throw new IOException("stream closed");
}
}
}
주:이상 은 간단 한 기능 실현 일 뿐 이 고 전면적으로 이해 하면 소스 코드 를 참고 할 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.