상세 컨텐츠

본문 제목

JAVA IO(Input/Output)

BackEnd/JAVA

by H_Develop 2022. 8. 9. 09:20

본문

IO는 입출력 스트림을 의미한다. 스트림(Stream)이란 

데이터를 입출력하기 위한 방법으로 프로그램에서 파일을 읽어온다든지, 

콘솔에서 키보드 값을 얻어오는 등의 작업을 말한다. 

자바 가상머신 JVM에서 콘솔로 값을 보낼 땐 Output, 반대로 콘솔의 값을 JVM에서 읽을 땐 Input을 사용한다.
  

 

 

text 파일  length() list()

		String path = "C:/dev/test_io.text";
		File f1 = new File(path);
		if(!f1.isFile()) {
			System.out.println("파일 크기 : " + f1.length() + " 바이트");
		}
		System.out.println();
		String path1 = "C:/dev";	// 폴더 지정
		File f2 = new File(path1);
		if(!f2.isFile()) {	// f1이 폴더, f1.isDirectory()
			String[] names = f2.list();
			System.out.println("폴더에 있는 목록 : ");
			for(int i=0; i<names.length; i++) {
				System.out.println(names[i]);
			}
		}

파일 크기 : 0 바이트

폴더에 있는 목록 : 
eclipse
eclipse-workspace
test_io.txt

 

if(!f1.isFile())
path변수가 폴더일땐 파일이 아니라면 혹은 디렉토리라면 으로 써야된다.

 

 

 

isDirectory()

		System.out.println();
		String path2 = "C:/dev";
		File f3 = new File(path2);
		if(f3.isDirectory()) {
			File[] arr = f3.listFiles();
			for(int i=0; i<arr.length; i++) {
				if(arr[i].isDirectory()) {
					System.out.println(arr[i].getName());
				}
			}
		}

eclipse
eclipse-workspace

 

 

 

 

 

 

 

폴더 생성

		String path = "C:/ABC";
		File f1 = new File(path);
		if(!f1.exists()) {
			System.out.println("새로운 폴더를 생성합니다.");
			f1.mkdirs();	// 폴더 생성 method
			System.out.println(f1.isDirectory() ? "생성성공" : "생성실패");
		} else {
			System.out.println("폴더가 이미 있습니다.");
			System.out.println(f1.isDirectory() ? "이미 생성됨" : "추가 생성 실패");
			if(f1.exists()) {
				System.out.println(f1.getPath());	// getPath() 경로 호출
			}
			System.out.println(f1.getName());	// getName() 이름 호출
		}

 

 

 

 

throws

 

		try {
			back(args[0]);	// 하나의 인자를 필요로 하는 back() method
		} catch (Exception e) {
			System.out.println("컴맨드 인수가 없어요");
			e.printStackTrace();	// 에러의 내용을 보임
		} finally {
			System.out.println("종료합니다.");
		}
		
	}
	static void back (String a) throws Exception {	
// 오류가 있을 때, 여기서 처리하지 말고, back()를 호출 한 곳에서 처리를 받아라
		System.out.println(a);
	}

 

 

 

 

FileWriter   getProperty   line.separator   out.write   out.close()

 

import java.io.*;
public class stjava {
  public static void main(String[] args) {
    try{
      FileWriter out =new FileWriter("C:/Users/nizzy/Desktop/math.txt");
      //파일을 생성하겠다.
      String lf = System.getProperty("line.separator");
// line.separator =>한줄씩건너가겠다. 
// getProperty=> 시스템정보를 가져옴 ()안에 있는 정보를 String으로 불러옴
      int a=10, b=5;
      out.write("덧셈");
      out.write(a+"+"+b+"="+(a+b)+lf);
      out.write("뺼셈");
      out.write(a+"-"+b+"="+(a+b)+lf);
      out.close(); //파일을 열면 닫아줘야함
    }catch(Exception e){
      System.out.println(e);//e가 뭔지 확인
    }
  }
}

 

 

 

파일 내용 출력

class Test{
	public static void main(String[] args) throws FileNotFoundException, IOException {
		
		String path = "C:/dev/math.txt";
		File f1 = new File(path);
		if(f1.exists()) {
			FileInputStream fis = new FileInputStream(f1);//읽기, 더 이상 읽을 것이 없으면 -1 반환
			int code =0;
			while((code =fis.read()) != -1){//파일에 내용이 있다면
				System.out.print((char)code);
			        /*형변환이유 : 그냥 code를 출력하면 UNICODE이어서 깨지므로 int 자료형에 담아서 char로 형변환해서 출력하면 ASCII코드로 출력된다 */
			}
			if(fis != null) {
			      fis.close(); //파일닫아줌
			}
		}
		System.out.println("프로그램끝");
					
	}
}

 

 

 

파일 내용 출력

class Test{
	public static void main(String[] args) throws FileNotFoundException, IOException {
		
		String path = "C:/dev/test_io.txt";
		File f1 = new File(path);
		byte b_Read[] = new byte[100];	// 이 부분이 적으면 파일을 읽다가 자른다.
		if(f1.exists()) {
			FileInputStream fis = new FileInputStream(f1);//읽기, 더 이상 읽을 것이 없으면 -1 반환
			fis.read(b_Read, 0, b_Read.length);
			// read() method에 시작위치, 끝위치 지정
			System.out.println(new String(b_Read).trim());
			if(fis != null) {
			      fis.close(); //파일닫아줌
			}
		}
		System.out.println("프로그램끝");
					
	}
}

 

 

 

testt.txt 파일 만들어 대소문자 구별하여 글자 및 숫자 개수 구하기

 

class Test{
	public static void main(String[] args) throws FileNotFoundException, IOException {
		try {
			FileWriter out = new FileWriter("C:/dev/testt.txt");
			String lf = System.getProperty("line.separator");
			out.write("하나 둘 셋");
			out.write("ONE TWO THREE");
			out.write("one two three");
			out.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
import java.util.*;
import java.io.*;
public class stjava {
	public static void main(String[] args) throws FileNotFoundException {
		System.out.println("경로 입력");
		Scanner sc = new Scanner(System.in);
		String str = sc.next().trim();	// trim()안넣어도 됨
		FileReader fr = null;
		
		try {
			fr = new FileReader(str);
			int console = 0;
			int upper = 0;
			int lower = 0;
			int num = 0;
			while ((console = fr.read()) != -1) {
				if (console >= 'A' && console <= 'Z') {
					upper++;
				}
				if (console >= 'a' && console <= 'z') {
					lower++;
				}				
				if (console >= '0' && console <= '9') {
					num++;
				}
			}
			System.out.println("대문자 : " + upper);
			System.out.println("소문자 : " + lower);
			System.out.println("숫자 : " + num);
		} catch (Exception e) {
			
		} finally {
			try {
				if(fr != null) {
					fr.close();
				}
			} catch (Exception e) {
			}
		}
	}
}

 

'BackEnd > JAVA' 카테고리의 다른 글

JAVA Server - Client 서버 클라이언트 연결  (0) 2022.08.09
JAVA BufferedReader  (0) 2022.08.09
JAVA 다형성(Polymorphism)  (0) 2022.08.04
JAVA Lambda 람다식  (0) 2022.08.04
JAVA Thread synchronized 쓰레드 동기화, wait() notify()  (0) 2022.08.03

관련글 더보기