Skip to content

파일 입출력

Im Sejin edited this page Mar 13, 2019 · 2 revisions

파일 입력

package practice.io;

import java.io.*;

public class ReaderClass {
	
	String path = null;
	
	public ReaderClass(String path) {
		this.path = path;
	}
	
	public String read() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(path));
		
		String text = "";
		while(true) {
			String line = br.readLine();
			if(line == null) break;
			text += line + "\r\n";		// readLine()은 개행문자를 읽지 못하기에 직접 추가한다
		}
		br.close();
		
		return text;
	}
	
	public String readByte() throws IOException {
		FileInputStream fis = new FileInputStream(path);
		byte[] b = new byte[1024];		// 1024바이트 만큼씩 읽는다
		
		fis.read(b);
		fis.close();
		
		return new String(b);			// 바이트를 String constructor를 통해 바꾼다
	}
	
}

java.io.ReaderBufferedReader
                          └InputStreamReaderFileReader

BufferedReader의 constructor 중 BufferedReader(Reader in)로 FileReader 인스턴스를 받았다.


파일 출력

package practice.io;

import java.io.*;

public class WriterClass {
	
	private PrintWriter pw = null;
	private String path = null;
	
	public WriterClass(String path) {
		this.path = path;
	}
	
	public void write(String text) throws IOException {
		System.out.println(" -- write() START -- ");
		System.out.println("text: " + text);
		
		pw = new PrintWriter(path);	// 기존 파일에 내용을 덧붙이려면 new PrintWriter(new FileWriter(path, true));
		pw.println(text + "\r\nCopied.");
		
		pw.close();
		System.out.println(" -- write() END -- ");
	}
	
}

java.io.WriterPrintWriter
                          └OutputStreamWriterFileWriter

PrintWriter의 constructor 중 PrintWriter(String fileName)으로 파일경로를 받아 인스턴스를 생성했다.
수정모드: PrintWriter(Writer out)으로 FileWriter 인스턴스를 받았다.

  • new PrintWriter(new FileWriter(path), true);
    이렇게 PrintWriter(Writer out, boolean autoFlush)로 하면 수정하지 않고 덮어쓴다. 왜 그럴까?

프로그래머 역사

2016.12.

  • HTML을 배우다
  • SQL을 접하다

2017.2.

  • CSS를 접하다
  • JSP를 접하다

2017.7.

  • PHP를 접하다

2017.9.

  • Java를 접하다
  • SQL을 배우다

2018.4.

  • ASP를 접하다
  • Java를 배우다

2018.12.

  • 대학(컴퓨터공학전공) 입시 불합격

2019.2.

  • Java를 공부하다
Clone this wiki locally