본문 바로가기
🖥Web/🔥Java

[Java] 간단한 파일 쓰기, 읽기 (File, FileOutputStream, FileInputStream, BufferedReader, InputStreamReader)

by 후눅스 2022. 10. 30.
반응형
package com.example.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileInputOutputTest {

	public static void main(String[] args) throws IOException {
		File f = new File("./src/com/example/test/new_file.txt");
		FileOutputStream fos = new FileOutputStream(f);
		String text = "메모장에 적고 싶은 말\n줄바꿈1\n줄바꿈2";
		fos.write(text.getBytes());
		fos.close();

		FileInputStream fis = new FileInputStream(f);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
 
        String line;
        while ((line = br.readLine()) != null) sb.append(line + System.lineSeparator());
 
        text = null;
        text = sb.toString();
		System.out.println("text :\n" + text);
		fis.close();
	}
}

 

 

반응형