[Java]::Remind - 파일 입출력

Gentlee's Self-Study Log·2023년 5월 17일
0

Java Reminder

목록 보기
14/19
post-thumbnail

File 객체

Java.io패키지에서 제공하는 File클래스는 파일 크기, 파일 속성, 파일 이름 등의 정보를 얻어내는 기능과 파일 생성 및 삭제 기능을 제공한다. 그리고 디렉토리를 생성하고 디렉토리에 존재하는 파일 리스트를 얻어내는 기능도 있다.
파일 또는 관련된 디렉토리를 지원하는 기능을 한다.

File - 메소드

  • isDirectory() - 디렉터리인지 여부 판단
  • isFile() - 파일인지 여부 판단
  • delete() - 삭제
  • renameTo() - 이동
  • length() - 사이즈/크기
  • canRead() - 읽을 수 있는지
  • canWrite() - 쓸 수 있는지
  • canExecute() - 실행 할 수 있는지
  • canHidden() - 숨길 수 있는지
  • setReadable(true) - 속성 설정(read)
  • setWritable(true) - 속성 설정(write)
  • setExecutable(ture) - 속성 설정(execute)
  • getAbsolutePath() - 절대 경로 출력
  • getAbsoluteFile() - 절대 경로를 갖는 파일 객체로 변환
  • getParent() - 부모 디렉터리 출력
  • getParentFile() - 부모 파일 출력
  • list() - 디렉터리 목록
  • listFiles() - 파일 목록
File f1 = new File("c:\\work");
File f2 = new File("c:\\work\\a.txt");

// 파일 또는 디렉토리의 존재 여부 판단
if(f1.isDirectory()){System.out.println(f1.getName()+"은 디렉토리");}
if(f2.isFile()){System.out.printlnn(f2.getName()+"은 파일");}

//파일 또는 디렉토리 삭제
File f3=new File("c:\\work\\subDir\\b.txt");
if(!f3.delete()){System.out.println("삭제실패");}

//파일 이동
f2.renameTo(f3);

//파일 크기
long size = f3.length();
System.out.println(size);

//파일 속성 읽기
System.out.println(f3.canRead()+":"+f3.canWrite()+":"+f3.canExecute()
+":"+f3.canHidden());

//파일 속성 설정
f3.setReadable(true);
f3.setWritable(true);
f3.setExecutable(true);

//파일 절대 경로
File f4 = new File("c:\\work\\subDir");
String f4Path = f4.getAbsolutePath();
File f5 = f4.getAbsoluteFile(); //절대 경로를 갖는 파일 객체로 변환

//부모 디렉터리
String parentDir = f4.getParent();
File parentFile = f4.getParentFile();

//디렉터리 목록 구하기
String[] fileNames = parentFile.list();
File[] files = parentFile.listFiles();

RandomAccessFile

RandomAccessFile은 파일의 임의의 위치에 데이터를 읽고 쓰기 위해서 위치값을 지정해서 접근하는 파일 객체이다. 위치를 지정해서 출력할 수 있고, 바이트 배열의 크기만큼 접근도 가능하다.

EX)

File f = new File("data.txt");
try(
	RandomAccessFile raf = new RandomAccessFile(f,"rw"); 
    // rw는 read/write 속성
){
	raf.seek(1); // 위치값지정
    byte b = raf.readByte();
    System.out.println((char)b);
    
    byte[] arr = new byte[4];  //배열크기만큼 읽기
    raf.read(arr);
    System.out.println(new String(arr));
    
    raf.seek(2);	
    raf.write("good".getBytes());	
    
}catch(Exception e){
	e.printStackTrace();
}

Property File(프로퍼티 파일)

확장자가 .property 인 파일은 텍스트 파일로서 데이터가 name=value형태로 저장된다.

Properties는 이런 프로퍼티 파일을 읽고 쓰기위한 객체이다.

EX(Read)

try(
	Reader reader = new InputStreamReader(new FileInputStream("user.properties");
){
	Properties user = new Properties();
    user.load(reader);
    
    System.out.println(user.getProperty("id"));
    System.out.println(user.getProperty("name"));
    System.out.println(user.getProperty("password"));
}

결과

user.properties 텍스트 파일안에 있는 아래 데이터를 읽는다.

id = purun
name = Jisoo
password = tiger
EX(Write)

try(
	Writer wirter = new OutputStreamWriter(new FileOutputStream("car
    .properties"));
){
	Properties car = new Properties();
    car.setProperty("model","G90");
    car.setProperty("engine","2300");
    car.setProperty("fuel","3.3");
    
    car.store(write,"car information"); 
}

결과

아래 데이터가 저장된 car.properties 텍스트 파일이 만들어진다.

#car information
model=G90
engine=2300
fuel=3.3

FileChannel

File Strema을 통해서 데이터를 접근할 때, 속도를 더 향상 시키기 위한 객체가 FileChannel이다. 속도 향상으 위해서 Buffer라는 개념이 들어간다.

파일 채널 읽기


try(
	RandomAccessFile file = new RandomAccessFile("a.txt","rw");
    
 	//FileChannel객체 구하기 getChannel()
    FileChannel channel = file.getChannel();
){
	int bufferSize = 1024; 
    
    // 버퍼 처리해주는 객체를 버퍼 크기를 정해서 allocate()로 만든다.
    ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
    
    // 표준출력장치(System.out)에 출력하기 위해 channel만든다. 
    WritableByteChannel out = Channels.new Channel(System.out);
    
    while(channel.read(buffer) != -1){
    	buffer.flip(); //채널에 대해 read/write를 병행하면서 사용
    	out.write(buffer);
    	buffer.clear(); 
    }
}
파일 채널 쓰기


 try(
 	FileOutputStream file = new FileOutputStream("c.txt");
    //FileChannel객체 구하기 getChannel()
    FileChannel channel = file.getChannel();
){
	int bufferSize = 1024; 
    
    // 버퍼 처리해주는 객체를 버퍼 크기를 정해서 allocate()로 만든다.
    ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
    
    String str = "채널에 쓸 문구적기";
    
    buffer.put(str.getBytes()); //버퍼에 데이터 집어넣기
    buffer.flip();
    channel.write(buffer); //채널을 통해 버퍼에 집어넣은 데이터를 write 한다.
    
}

Zip Input/OutputStream

ZipInputStream : 파일을 압축하여 압축파일을 생성하는 객체
ZipOutputStream : 압축된 파일을 해제하는 객체

압축 파일 생성

try(
	ZipOutputStream zos = 
    new ZipOutputStream(new FileOutputStream("a.zip");
){
	ZipEntry = new ZipEntry("a.txt");  //ZipEntry 객체로 추가
    zos.putNextEntry(entry);
    byte[] data = Files.readAllBytes(Paths.get("a.txt");
    zos.write(data);  //실제 데이터 writing 하는 부분
    
    ZipEntry = new ZipEntry("b.txt");
    zos.putNextEntry(entry);
    zos.write(Files.readAllBytes(Paths.get("b.txt");
    
    ZipEntry = new ZipEntry("c.txt");
    zos.putNextEntry(entry);
    zos.write(Files.readAllBytes(Paths.get("c.txt");  
}
압축 파일 해제

try(
	ZipInputStream zis = new ZipInputStream(new FileInputStream("a.zip");
){
	ZipEntry entry = null;
    while((entry = zis.getNextEntry()) != null){
    	
        try(
        	FileOutputStream out 
            = new FileOutputStream("c:\\work\\"+entry.getName());           
        ){
        	byte[] buf = new byte[1024];
            int len = 0;
            while((len=zis.read(buf)) != -1){
            	out.write(buf,0,len);
            }
        }
        
    }
}
profile
https://github.com/SamGentlee

0개의 댓글