Java/Java

자바 File 다루기

code2772 2022. 10. 7. 08:24
728x90
반응형
3. 파일 다루기

File 클래스
파일 또는 디렉토리 다루는 클래스
입출력 관한 작업

    File 참조변수 = new File(파일 경로 또는 파일이름);

✔ 스트림(Stream)
- 자바는 파일이나 콘솔에 입출력을 직접 다루지 않고 스트림이라는 흐름을 통해 다룸
- 운영체제에 의해 생성되는 가상의 연결고리를 의미하고 중간 매개자 역할을 함


    Java 프로그램 <---------> OS(운영체제) <----------> 디스크(파일, 디렉토리)
                  스트림(흐름)                        모니터, 프린터, 네트워크...


✔ 절대경로
믈리적인 경로
예) C:\Java\Day9\Day9.txt

✔ 상대경로
현재 동작하고 있는 파일을 중심으로 상대적인 경로
예) Day9.txt, 디렉토리명/Day9.txt, ../Day9.txt

 

import java.io.File;
import java.io.IOException;

public class File1 {
    public static void main(String[] args) {
        File file1 = new File("input1.txt");// 상대경로
        System.out.println(file1.exists());// true


        System.out.println(file1.isDirectory()); // false
        System.out.println(file1.length()); // 85 바이트

        File dir1 = new File( "C:\\Java\\Day9\\Test1");// 절대경로
        dir1.mkdir();// 파일을 만듬

        File file2 = new File(dir1,"input2.txt");// 이 파일에 객체를 만든다.
        try {
            file2.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(file2.getPath()); // 상대경로
        System.out.println(file2.getAbsoluteFile()); // 절대경로 C:\Java\Day9\Test1\input2.txt

    }

 

exist() : 파일에 실제 존재하는지 여부(boolean - true, false)
isDirectory() : 해당 경로가 디렉토리인지 여부
length() : 파일 데이터 길이를 변환(byte), 한글은 3byte, 영어/특수문자/공백 1byte
mkdir() : 디렉토리를 생성
creatNewFile() : 파일을 생성

FileInputStream 클래스
- java.io의 가장 기본이 되는 입력 클래스
- 입력 스트림 생성

read() : 스트림을 통해 byte단위로 데이터를 읽어

 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class File2 {
    public static void main(String[] args) {
        byte[] arr = new byte[20]; // 20byte

        try {
            FileInputStream fis = new FileInputStream("input3.txt");
            System.out.println((char)fis.read()); // H ()에 아무것도 없으면 선언한 1byte만 가저온다.
            fis.read(arr,0,6);// arr1에 어디서 어디까지 가저올거냐? e l l o ' ' 6개를 가저오고 나머지 14는 빈공간
            for(byte b:arr){ // 20개를 선언한다.
                System.out.print((char)b+ " ");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

 

FileOutputStream 클래스
- java.io의 가장 기본이 되는 입력 클래스
- 츨력 스트림을 통해 byte단위로 데이터를 씀

FileReader 클래스
- FileInputStream과 유사
- 문자 스트림으로서 문자 단위의 바이트 변환 기능을 가지고 있음
- 바이트 단위가 아닌 문자단위로 입출력을 실행

FireWriter 클래스
- FileOutputStream과 유사
- 문자 스트림으로서 문자 단위의 바이트 변환 기능을 가지고 있음
- 바이트 단위가 아닌 문자단위로 입출력을 실행

PrintWriter 클래스
- 문자열을 출력하는 스트림 Writer 속성을 가진 클래스
- OutputStream의 자식 클래스이며 byte단위 출력 클래스인 PrintStream의 print메서드를
모두 구현하여 사용할 수 있음

 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class File3 {//출력

    public static void main(String[] args) {
        String input = "input3.txt";
        String output = "output1.txt";

        try {
            FileInputStream fis = new FileInputStream(input);
            FileOutputStream fos = new FileOutputStream(output);

            int b;
            while ((b = fis.read()) != -1) { // -1은 더 이상 읽을게 없다면
                fos.write(b);
                System.out.println((char) b + " ");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }}

 

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class File4 {
    public static void main(String[] args) {
        char[] arr = new char[50];
        try{
            FileReader fr = new FileReader("input1.txt");
            System.out.println((char) fr.read());
            fr.read(arr);
            for(char c :arr){
                System.out.print(c);
            }

        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

 

import java.io.FileWriter;
import java.io.IOException;

public class File5 {
    public static void main(String[] args) {
        String str = "내일만 공부하면 4일쉰다.";

        try{
            FileWriter fw = new FileWriter("output2.txt");
            fw.write(str.charAt(0)); // 내
            fw.write("\n"); // 다음 줄
            fw.write(str); // 전체 출력
            fw.write("\n");
            fw.write(str.charAt(0));
            fw.write("\t"); // tab
            fw.write("일만 공부하면 4일 쉰다.");
            fw.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class File6 {
    public static void main(String[] args) {
        String file = "input1.txt";

        try {//            FileInputStream fis = new FileInputStream(file);
//            Scanner sc = new Scanner(fis);
            Scanner sc = new Scanner(new FileInputStream(file));

            while (sc.hasNextLine()) { //한 줄을 읽고 있으면 와일문으로
                String str = sc.nextLine();
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class File7 {
    public static void main(String[] args) {
        String file = "output3.txt";
        String[] arr = {"김사과", "오렌지", "반하나", "이메론"};

        FileOutputStream fos = null;
        try {
//            fos = new FileOutputStream(file);
//            PrintWriter pw = new PrintWriter(fos);
            PrintWriter pw = new PrintWriter((new FileOutputStream(file)));
            for(int i=0;i<arr.length;i++){
                System.out.print(arr[i]+" ");
                //pw.println(arr[i]);
                pw.print(arr[i]+" ");
            }
            pw.close();//닫지 않으면 저장이 되지않음
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
}

 

//특정 값을 기준으로 문자열을 자으로 배열에 저장
String str5 = "김사과,반하나,오렌지,이메론";
String[] arr = str5.split(",");//split "," 컴마를 기준으로 자르겠다는 메소드 컴마는 없어짐
for(String s : arr){
    System.out.print(s+" ");
}

 

과제 1.
"product.txt" 에서 데이터를 읽어 product 객체에 각각 데이터를 저장하고 ArrayList에 담아
출력하는 프로그램을 작성해보자.

1. 파일을 읽어드림
2. 스플릿하여 각 배열에 저장

-> product class 따로 만들어야 함 name, price, name -> arrayList 에 5개를 저장해서 -> tostring해서 표현

product.txt 내용
갤럭시노트,1200000,삼성
아이버드,130000,삼성
그램노트북,1000000,엘지
60인치TV,3000000,소니
맥북프로,1800000,애플

 

public class Product {
//    과제 1.
//            "product.txt" 에서 데이터를 읽어 product 객체에 각각 데이터를 저장하고 ArrayList에 담아
//    출력하는 프로그램을 작성해보자.
//
//1. 파일을 읽어드림
//2. 스플릿하여 각 배열에 저장
//
//-> product class 따로 만들어야 함 name, price, name -> arrayList 에 5개를 저장해서 -> tostring해서 표현
//
//    product.txt 내용
//    갤럭시노트,1200000,삼성
//    아이버드,130000,삼성
//    그램노트북,1000000,엘지
//60인치TV,3000000,소니
//    맥북프로,1800000,애플
    private String productName;
    private int price;
    private String name;

    public Product() {
    }

    public Product(String productName, int price, String name) {
        this.productName = productName;
        this.price = price;
        this.name = name;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Product(" +
                "기종 : '" + productName  +
                ", 가격 : " + price +
                ", 브랜드 : " + name + ")"
                ;
    }
}

 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Phone {
    public static void main(String[] args) {

        ArrayList<Product> pr = new ArrayList<>();
        String file = "product.txt"; 

        try {
            Scanner sc = new Scanner(new FileInputStream(file));
            while (sc.hasNextLine()) { //product.txt에서 한 줄을 보고 있는지 판단한다.
                int i=0; // 배열의 길이가 얼마나 긴지는 평소에는 잘 알지 못한다.
                String str = sc.nextLine();// 한 줄을 읽어 str에 삽입한다.
                String[] arr = str.split(","); // 읽어온 파일을 split하여
                // string 배열형에 저장한다
                Product p = new Product(arr[i],Integer.parseInt(arr[i+1]),arr[i+2]);
                //product 클래스에 ArrayList형 배열로 저장한다.
                pr.add(p);// 저장한다

            }
            for(Product p : pr){
                System.out.println(p);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();//오류 설명
        }
    }

}
반응형