개발일지/Java + Spring
                
              [Java] File 만들기/읽기
                연습용365
                 2021. 9. 30. 15:43
              
              
            
            import java.io.*;
import java.util.Scanner;
public class PhoneWriterEx {
	public static void main(String[] args) {
		FileWriter fw = null; //초기값
		File f = new File("c:\\temp\\phone.txt"); 
		//저 장치 밑에 저장해 줌
		
		try {
		fw = new FileWriter(f);
		Scanner sc = new Scanner(System.in);
		System.out.println("전화번호 입력 프로그램입니다.");
		
		while(true) {
			System.out.print("이름 전화번호 >> ");
			String line = sc.nextLine(); //한 줄을 읽는다.
			if(line.equals("그만"))
				break; //입력종료
				fw.write(line + "\r\n"); //한 줄 띄어 저장하기 위해 "\r\n"을 붙인다.
		}
		System.out.println(f.getPath() + "에 저장했습니다.");
		sc.close();
		fw.close();
		}catch(IOException e){ //파일을 저장할 수 없는 경우 예외. 이상이 생겼을 때
			System.out.println("파일에 문제가 생겼습니다.");
		}
	}
}파일이 없어서 오류 뜰 수 있으니 그 경우 파일을 임의로 만들어준다.
파일을 닫는 습관을 들인다.
import java.io.*;
public class PhoneReaderEx {
	public static void main(String[] args) {
		FileReader fr = null;
		File f = new File("c:\\temp\\phone.txt");
		try {
			fr = new FileReader(f) ;
			System.out.println(f.getPath() + "를 출력합니다.");
			while(true) {
				int c = fr.read();
				if(c == -1) 
					break;
					System.out.print((char)c);
				}
				fr.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
}위에서 만들어 준 파일을 읽어준다.
e.printStackTrace();의 경우
| java.io.FileNotFoundException: c:\temp\temp.txt (지정된 파일을 찾을 수 없습니다) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:211) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153) at java.base/java.io.FileReader.<init>(FileReader.java:75) at UpperCharacter.main(UpperCharacter.java:8) | 
import java.io.*;
public class BufferedReader {
	public static void main(String[] args) {
		File f = null;
		BufferedReader fr = null;
		try {
			f = new File("c:\\temp\\phone.txt");
			fr = new BufferedReader(new FileReader(f));
			System.out.println( f.getPath() + "를 출력합니다.");
			while(true) {
				String line = fr.readLine();
				if(line == null) //end of file
					break;
				System.out.println(line + "\n");
			}
			fr.close();
		}catch(IOException e){ //파일을 저장할 수 없는 경우는 제외
			e.printStackTrace();
		}
	}
}
//파일을 Buffer(임시기억장소)에 넣었다가 출력하는 내용 
//우리가 평소 사용하는 메모리가 아니라 CPU가 하드디스크의 용량을 끌어다가 공간을 쓴다.
//하드공간이 꽉 차 있으면 만들 수 없음오류 뜨는 코드임!!!
import java.io.*;
import java.util.Scanner;
public class ExUsingScanner {
	public static void main(String[] args) {
		FileReader fr = null; 
		File f = new File("c:\\temp\\phone.txt");
		try {
			fr = new FileReader(f);
			Scanner sc = new Scanner(fr);
			System.out.println( f.getPath() + "를 출력합니다.");
			while(sc.hasNext()) {
				String line = sc.nextLine(); //한 줄 읽기
				System.out.println(line);
			}
			fr.close();
			sc.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}한 줄씩 읽기
import java.io.*;
public class UpperCharacter {
	public static void main(String[] args) {
		try {
			File f = new File("c:\\temp\\temp.txt");
			FileReader fin = new FileReader(f); //객체 만듦
			int c;
			while((c=fin.read()) != -1) { //문자가 있니?
				char a = (char)c; //문자를 a에 넣어줌
				if(Character.isLowerCase(a)) //소문자?
					a = Character.toUpperCase(a); //소문자로 돼 있다면 대문자로 바꿔라
				System.out.print((char)a); // 바꾼 것을 대문자로 읽어라
			}
			fin.close();
		}catch(IOException e) {
			System.out.println("파일 읽기 오류");
		}
		
	}
}소문자를 대문자로 바꾸다.
import java.io.*;
import java.util.Scanner;
public class LineNumber {
	public static void main(String[] args) {
		System.out.println("파일을 읽어 줄력합니다.");
		try {
			Scanner fs = new Scanner(new FileReader("c:\\windows\\system.ini")); //파일로부터 읽기
			int lineNumber = 1;
			while(fs.hasNext()) { //파일에 읽을 것이 있는 동안
				String line = fs.nextLine();
				System.out.printf("%4n", lineNumber++); 
				//행번호 출력
				//"%4n"는 뒤에 있을 "lineNumber++" 하나의 포맷으로 4바이트 정수형을 찍겠다는 소리
				System.out.println(": " + line); //소스 한행 출력
			}
			fs.close();
		} catch(IOException e) {
			System.out.println("입출력 오류가 발생했습니다.");
		}
	}
}
//행번호 출력 
//"%4n"는 뒤에 있을 "lineNumber++" 하나의 포맷으로 4바이트 정수형을 찍겠다는 소리 
출력하면 앞이 띄어서 출력이 됨