본문 바로가기
PROGRAMING📚/Java📑

Java:: 입출력 Stream I/O

Ta이니 2024. 6. 27.
728x90
반응형

입출력 단위 : Stream

Byte 기반(Binary 기반)

- InputStream : 프로세스 안으로 들어오는 것

-OutputStream : 프로세스 밖으로 나가는 것

 

Char 기반(Char 기반)

- Reader

-Writer

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class Ex01Byte {
  public static void main(String[] args) {
    byte[] inSrc ={0,1,2,3,4,5,6,7,8,9};
    byte[] outSrc= null;

    ByteArrayInputStream input = new ByteArrayInputStream(inSrc);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
  }
}

 

위와 같이 입력을 해주고 inSrc를 출력해주었다

System.out.println(Arrays.toString(inSrc));

 

input 안에있는 데이터 만큼 불러와서

output.write()를 사용해서 outSrc배열 안에 값을 넣어주고

배열을 출력해주었다

int data =0;
while((data = input.read()) != -1)
    {
      output.write(data);
    }
outSrc = output.toByteArray();
System.out.println(Arrays.toString(outSrc));

 

byte[] tmp = new byte[4];
input = new ByteArrayInputStream(inSrc);
output = new ByteArrayOutputStream();
while(input.available() >0){
  try {
    //input을 읽어서 tmp에 담음, read가 읽은 글자수를 반환함
    int length = input.read(tmp);
    output.write(tmp);
    outSrc = output.toByteArray();
    System.out.println("tmp : "+Arrays.toString(tmp));
    System.out.println("outSrc : "+Arrays.toString(outSrc));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

 

output.write(tmp,0,length); 처럼 길이를 적어주면

tmp의 길이 만큼만 출력되게 만들어 줄 수있다

 byte[] tmp = new byte[4];
    input = new ByteArrayInputStream(inSrc);
    output = new ByteArrayOutputStream();
    while(input.available() >0){
      try {
        //input을 읽어서 tmp에 담음, read가 읽은 글자수를 반환함
        int length = input.read(tmp);
//        output.write(tmp);
        output.write(tmp,0,length);
        outSrc = output.toByteArray();
        System.out.println("tmp : "+Arrays.toString(tmp));
        System.out.println("outSrc : "+Arrays.toString(outSrc));
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }


FileInputStream

 

try catch finally 반드시 close 해야함.

package p08_IO;

import java.io.*;

public class Ex02FileInputStream {
  public static void main(String[] args) {
    FileInputStream fis = null;
    InputStreamReader reader = null;
    BufferedReader br = null;
    try {
      fis = new FileInputStream(
          "C:\\workspace\\spaceJava\\" +
              "20240611_java\\src\\p08_IO\\Ex02FileInputStream.java");
      reader = new InputStreamReader(fis);
      br = new BufferedReader(reader);
      int data;
      while ((data = br.read()) != -1) {
        char c = (char) data;
        System.out.print(c);
      }
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      try {
        br.close();
        reader.close();
        fis.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
}

 

tryWithResource

package p08_IO;

import java.io.*;

public class Ex02FileInputStream {
  public static void main(String[] args) {
    // tryWithResource
    try(
        FileInputStream fis2 = new FileInputStream(
            "C:\\workspace\\spaceJava\\" +
                "20240611_java\\src\\p08_IO\\Ex02FileInputStream.java");
        InputStreamReader reader2 = new InputStreamReader(fis2);
        BufferedReader br2 = new BufferedReader(reader2);
    ) {

      int data;
      while ((data = br2.read()) != -1) {
        char c = (char) data;
        System.out.print(c);
      }
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
package p08_IO;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class Ex03FIleOutputStream {
  public static void main(String[] args) {
    try( FileOutputStream fos = new FileOutputStream("123.txt");
         BufferedOutputStream bos = new BufferedOutputStream(fos,5);)
    {
      for (int i = '0'; i < '9'; i++) {
        bos.write(i);
      } 
    }catch (Exception e){
      e.printStackTrace();
    }
  }
}

 

package p08_IO;

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

public class Ex04FileReader {
  public static void main(String[] args) {
    String fileName = "test.txt";
    try {
      FileInputStream fis = new FileInputStream(fileName);
      FileReader fr = new FileReader(fileName);

      int data = 0;
      while ((data = fis.read()) != -1) System.out.print((char) data);
      System.out.println();
      fis.close();

      while ((data = fr.read()) != -1) System.out.print((char) data);
      System.out.println();
      fr.close();

    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

package p08_IO;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class Ex05Notepad {
  public static void main(String[] args) {
    new Notepad();
  }
}

class Notepad extends JFrame {
  private JMenuBar menuBar;
  private JMenu menuF, menuE, menuO, menuV, menuH;
  private JMenuItem miNew, miOpen, miSave, miExit, miInfo;
  private JTextArea textArea;
  private JScrollPane scp;
  private JFileChooser fc;

  public Notepad() throws HeadlessException {
    init();
    arrange();
    inflate();
  }

  //window의 구성품을 초기화
  private void init() {
    menuBar = new JMenuBar();
    menuF = new JMenu("파일(F)");
    menuE = new JMenu("편집(E)");
    menuO = new JMenu("서식(O)");
    menuV = new JMenu("보기(V)");
    menuH = new JMenu("도움말(H)");
    miNew = new JMenuItem("새로만들기(N)");
    miOpen = new JMenuItem("열기(O)");
    miSave = new JMenuItem("저장(S)");
    miExit = new JMenuItem("끝내기(X)");
    miInfo = new JMenuItem("정보(A)");

    textArea = new JTextArea();
    scp = new JScrollPane(textArea);
    fc = new JFileChooser();

    miNew.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        textArea.setText(""); //새로 만들었을 때, 글 지우기
        System.out.println("널위해 만들었어!!😊");
      }
    });
    //열기
    miOpen.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        int ret = fc.showOpenDialog(miOpen);
        if (ret == 0) {
          try {
            FileReader fr = new FileReader(fc.getSelectedFile().toString());
            int data;
            textArea.setText("");
            while ((data = fr.read()) != -1) {
              textArea.append(String.valueOf((char) data));
            }
            fr.close();
          } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
          } catch (IOException ex) {
            throw new RuntimeException(ex);
          }
        }
      }
    });
    //파일 저장하기
    miSave.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        int ret = fc.showSaveDialog(miSave);
        if (ret == 0) {
          try {
            String selectedFile = fc.getSelectedFile().toString();
            FileWriter fw = new FileWriter(selectedFile);
            //보조스트림 , 입출력에 대한 뭐시기???
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(textArea.getText());
            bw.close(); fw.close();
          } catch (IOException ex) {
            ex.printStackTrace();
          }
        }
      }
    });
  }

  //배치
  private void arrange() {
    menuF.add(miNew);
    menuF.add(miOpen);
    menuF.add(miSave);
    menuF.add(miExit);
    menuH.add(miInfo);
    menuBar.add(menuF);
    menuBar.add(menuE);
    menuBar.add(menuO);
    menuBar.add(menuV);
    menuBar.add(menuH);
    setJMenuBar(menuBar);

    //JFram에 의해서 사용가능
    add(scp);
  }

  //나타나게 함
  private void inflate() {
    setTitle("나의 메모장");
    setSize(500, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(this);
    setVisible(true);
  }

}

 

모달창 띄우기

miInfo.addActionListener(e -> {
  new InfoDialog(this, true); //modal이 false인 경우, 다른창을 선택 가능함
});

 

class InfoDialog extends JDialog{
  public InfoDialog(JFrame fr, boolean modal) {
    super(fr, modal);
    JPanel pnl = new JPanel();
    JLabel label = new JLabel("널 위해 만들었어!");
    pnl.add(label);
    add(pnl,"Center");
    setTitle("정보");
    setSize(200, 100);
    setLocationRelativeTo(this);
    setVisible(true);
  }
}

 


//1) File 폴더를 다룰 수 있다.
File file = new File(".");
if(file.exists() && file.isDirectory()){
  String [] fileList = file.list();
  for (int i = 0; i < fileList.length; i++) {
    System.out.println(fileList[i]);
  }
}
else{
  System.out.println("이것은 경로가 잘못 되었습니다.");
}

 

절대경로: 루트로 부터의 나의 경로

상대경로: 현재 내가 있는 위치를 기준

 //2) File 객체는 파일을 다룰 수 있다
    file = new File("test.txt");
    if (file.exists()) {
      try {
        System.out.println(file.getName());
        System.out.println(file.getPath());
        System.out.println(file.getAbsolutePath()); //절대경로:: 루트로 부터의 경로
        System.out.println(file.getCanonicalPath());
        System.out.println(file.getParent());
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

 

//2) File 객체는 파일을 다룰 수 있다
file = new File("test.txt");
if (file.exists()) {
  try {
    System.out.println(file.canExecute());//실행
    System.out.println(file.canRead()); //읽기
    System.out.println(file.canWrite()); //쓰기
    System.out.println(file.isFile()); //파일이 맞는가 아닌가
    System.out.println(file.length()); //파일의 크기
    System.out.println(file.toString().substring(
            file.toString().lastIndexOf(".")+1)); //파일의 확장자명
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

 

// 3)File 객체는 Drive 의 정보를 알 수 있다
String drive;
double totalSpace,freeSpace, usableSpace,usedSpace;
File[] roots = File.listRoots();
for(File f: roots){
  drive = f.getAbsolutePath();
  totalSpace = f.getTotalSpace()/Math.pow(1024,3);
  freeSpace = f.getFreeSpace()/Math.pow(1024,3);
  usableSpace = f.getUsableSpace()/Math.pow(1024,3);
  usedSpace = totalSpace - usableSpace;
  System.out.println("Dirve :" +drive);
  System.out.printf("Total Space : %5.2f GB \n",totalSpace);
  System.out.printf("FreeSpace Space : %5.2f GB \n",freeSpace);
  System.out.printf("UsableSpace Space : %5.2f GB \n",usableSpace);
  System.out.printf("UsedSpace Space : %5.2f GB \n",usedSpace);
}

 

728x90
반응형

'PROGRAMING📚 > Java📑' 카테고리의 다른 글

Java :: 활용 -String  (0) 2024.06.25
Java::확장-extends(상속)  (0) 2024.06.25
Java::구성 - 배열[Array]  (0) 2024.06.21
Java::구성- switchCase  (0) 2024.06.20
Java:: 구성- 정보은닉(incapsulation),getter/setter 사용하기  (0) 2024.06.20

댓글