[java] Buffered, Stream

김남균·2023년 9월 12일
0

java

목록 보기
15/15

공부한 내용을 정리하는 글이라 틀린 내용이 있을 수 있습니다!

오늘 학습한 Buffered, byteStream, dataStream 대한 정리.


Buffered


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;


public class BufferedTest {
	public static void test() {
		try {
			String path =BufferedTest.class.getResource("").getPath();
			System.out.println(path+"fkpz_o890_220609.jpg");
			FileInputStream fis = new FileInputStream(path+"fkpz_o890_220609.jpg");
			FileOutputStream fos = new FileOutputStream(path+"output1.jpg");
			
			FileInputStream fis2 = new FileInputStream(path+"fkpz_o890_220609.jpg");
			FileOutputStream fos2 = new FileOutputStream(path+"output1.jpg");
			BufferedInputStream bis = new BufferedInputStream(fis2);
			BufferedOutputStream bos = new BufferedOutputStream(fos2);
			
			System.out.println(copy(fis,fos));
			System.out.println(copy(bis, bos));
			
			fis.close();
			fos.close();
			bis.close();
			bos.close();
			fis2.close();
			fos2.close();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
		
		private static long copy(InputStream is, OutputStream os) throws Exception {
			long start = System.nanoTime();
			
			while(true) {
				int data = is.read();
				if(data == -1)break; // -1 배열을 벗어나면 -1이뜸. ex) 배열 크기가 4인데 넘어가면 5로 넘어가면 -1취급 그래서 넘어가면 break!!!!
				os.write(data);
			}
			
			
			long end = System.nanoTime();
			return end - start;
		
		}
	
}

byteStream


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.FileInputStream;


public class OutputStreamTest {
	// 통신이랑 뭘까?
	//	- 데이터를 주고받는 것
	//	- 언제 통신한다고 얘기할 수 있을까?
	//		=> 데이터를 보내고 답신을 받을 때? -> 어디로? 서버? 클라이언트? DB?
	//		=> 위 내용은 일반적으로 생각할 수 있는 통신이다.
	//		=> 키보드 입력 시 데이터가 메인보드를 통해 CPU에 전달된다.
	public static void test() {
		// C:\Users\KGA\git\Real\HomeWork2\Game\src\c230911\byteStream
		String path = "C:/Users/KGA/git/Real/HomeWork2/Game/src/c230911/byteStream/test.db";
		// Window 외 나머지(Linux, Unix, Mac, Ububtum Android, ...)
		System.out.println();
		
		try {
			OutputStream os = new FileOutputStream(path); // 파일을 내보내는 
			
			os.write(10);
			os.write(20);
			os.write(30);
			
			os.flush(); // 메모리가 가득 차지 않았어도 강제로 파일로 저장한다. HDD와 통신한다.
			os.close();
			
			InputStream is = new FileInputStream(path);
			
			System.out.println(is.read());
			System.out.println(is.read());
			System.out.println(is.read());
			System.out.println(is.read());
			
			while(true) {
				int data =  is.read();
				if(data == -1) break;
				System.out.println("data : " + data);
			}
			
			is.close(); // 통신을 끝내라
			
		}catch(Exception e) {
			e.printStackTrace();
			
		}
		
		
		
		try {
			OutputStream os = new FileOutputStream(path);
			
			byte[] arr = {10, 20, 30};
			os.write(arr);
			
			os.flush();
			os.close();
			
			InputStream is = new FileInputStream(path);
			byte[] arr1 = new byte[100]; //최대 몇 바이트까지 가져올지 배열로 생성한다.
			
			int count = is.read(arr1);
			
			for(int i = 0; i < count; i++) {
				System.out.println("arr1[" + i + "] : " + arr1[i]);
			}
//			"가" << UTF-8 << 3byte << FF FF FF => AC 00 앞의 FF는 뭔지 알려주는것임.
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
	}
}

dataStream


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class DataStreamTest {

	public static void test() {
		try {
			String path = DataStreamTest.class.getResource("").getPath() + "test.db";
			FileOutputStream fos = new FileOutputStream(path);
			DataOutputStream dos = new DataOutputStream(fos);

			dos.writeInt(1); // 숫자를 넣을때
			dos.writeUTF("강아지"); // 글자를 넣을때
			dos.writeDouble(90.0);

			dos.writeInt(2);
			dos.writeUTF("고양이");
			dos.writeDouble(93.0);

			dos.writeInt(3);
			dos.writeUTF("호랑이");
			dos.writeDouble(100.0);

			dos.flush(); // 파일에 저장
			fos.close();
			dos.close();

			FileInputStream fis = new FileInputStream(path);
			DataInputStream dis = new DataInputStream(fis);

			for (int i = 0; i < 3; i++) {
				int num = dis.readInt();
				String name = dis.readUTF();
				double score = dis.readDouble();

				System.out.println(num + " ." + name + " : " + score + "점");
			}

			dis.close();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

ObjectStream


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectStreamTest {

	public static void test() {
		try {
			String path = DataStreamTest.class.getResource("").getPath() + "test.db";
			FileOutputStream fos = new FileOutputStream(path);
			ObjectOutputStream oos = new ObjectOutputStream(fos);

			Animal s1 = new Animal(1, "강아지", 90.0);
			Animal s2 = new Animal(2, "고양이", 93.0);
			Animal s3 = new Animal(3, "호랑이", 100.0);

			oos.writeObject(s1);
			oos.writeObject(s2);
			oos.writeObject(s3);

			oos.flush();
			oos.close();
			fos.close();

			FileInputStream fis = new FileInputStream(path);
			ObjectInputStream ois = new ObjectInputStream(fis);

			Animal sr1 = (Animal) ois.readObject();
			System.out.println(sr1.num);
			System.out.println(sr1.name);
			System.out.println(sr1.score);

			sr1 = (Animal) ois.readObject();
			System.out.println(sr1.num);
			System.out.println(sr1.name);
			System.out.println(sr1.score);

			sr1 = (Animal) ois.readObject();
			System.out.println(sr1.num);
			System.out.println(sr1.name);
			System.out.println(sr1.score);

			ois.close();
			fis.close();
//			데이터들끼리에 확실한 매칭을해주어야함. class한테 시리얼번호 붙여주는것.
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

import java.io.Serializable;

public class Animal implements Serializable {

	private static final long serialVersionUID = 1L; //자동으로 생성되는게 더 안전하게 만들어진다.
	int num;
	String name;
	double score;

	Animal(int num, String name, double score) {
		this.num = num;
		this.name = name;
		this.score = score;
	}
}

Path


import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathTest {

	public static void test() {
		// String path
		Path path = Paths.get("src/c230911/../c230908");// 자동으로 잡아준다 / 나 \를
		System.out.println(path.toAbsolutePath().normalize()); //toAbsolutePath 절대경로를 받아온다. normalize 경로 바꿔준다.
		
		File file = new File(path.toString()+"\\Main2.java");
		System.out.println(file.exists());
		try {
//			file.createNewFile();
			file.mkdir();
		}catch(Exception e) {
			e.printStackTrace();
		}
		
//		exit
		
	}
}

Main 코드는


import c230911.buffered.BufferedTest;
import c230911.byteStream.OutputStreamTest;
import c230911.dataStream.DataStreamTest;
import c230911.dataStream.ObjectStreamTest;
import c230911.fileIo.FileIoTest;
import c230911.fileIo.SubTest;

public class Main {
	public static void main(String[] args) {
	
		OptionsTest.test();
		MatchTest.test();
		OutputStreamTest.test();
		FileIoTest.test();
		SubTest.test();
		BufferedTest.test();
		DataStreamTest.test();
		ObjectStreamTest.test();
		
		PathTest.test();
	}
}

추가적인 내용

Match

import java.util.Arrays;

public class MatchTest {

   public static void test() {
      int[] arr = {1,3,5,7};
      int[] arr1 = {2,4,6,8};

      System.out.println(Arrays.stream(arr).allMatch(item ->item % 2 == 0)); //모든게 맞으면 true
      System.out.println(Arrays.stream(arr1).allMatch(item ->item % 2 == 0));
   
      System.out.println(Arrays.stream(arr).anyMatch(item ->item % 2 == 0)); //하나라도 맞으면 true
      System.out.println(Arrays.stream(arr1).anyMatch(item ->item % 2 == 0));

      System.out.println(Arrays.stream(arr).noneMatch(item ->item % 2 == 0)); //하나도 맞지않을때 true
      System.out.println(Arrays.stream(arr1).noneMatch(item ->item % 2 == 0));
   
   }

예외 처리의 다양한 코드 작성방법


import java.util.Arrays;
import java.util.OptionalDouble;

public class OptionsTest {
	public static void test() {
		int[] arr = { 1, 3, 5, 7};
		int[] arr1 = { 2, 4, 6, 8};
		
		System.out.println(Arrays.stream(arr)
				.filter(item->item%3==0).count());
		System.out.println(Arrays.stream(arr1)
				.filter(item->item%3==0).count());
		
		System.out.println(Arrays.stream(arr).average());
		System.out.println(Arrays.stream(arr1).average());
		
		System.out.println(Arrays.stream(arr).average().getAsDouble());
		System.out.println(Arrays.stream(arr1).average().getAsDouble());
		
		System.out.println(Arrays.stream(arr).max().getAsInt());
		System.out.println(Arrays.stream(arr1).max().getAsInt());
		
		int[] arr2 = {};
		try {
			System.out.println(Arrays.stream(arr2).average());	// 1. try/catch (예외처리)
			
			
			OptionalDouble od = Arrays.stream(arr2).average();	// 2. if/else (예외처리)
			if(od.isPresent()) {
				System.out.println(od.getAsDouble());
			}
			else {
				System.out.println("없어");
			}
			
			
			System.out.println(Arrays.stream(arr).average().orElse(0.0));	// 3. orElse (예외처리)
			System.out.println(Arrays.stream(arr2).average().orElse(0.0));
			
			
			Arrays.stream(arr)
				.average().
				ifPresent(item->System.out.println("예외 : "+item));	// 4. ifPresent (예외처리)
			Arrays.stream(arr2)
				.average().
				ifPresent(item->System.out.println("예외 : "+item));
			
			
			
			System.out.println(Arrays.stream(arr)
					.reduce(0, (a, b)->{
						return a + b / 2 + 1;
					}));
			System.out.println(Arrays.stream(arr)
					.reduce(0, (a, b)->	a + b / 2));
			// 1, 3, 5, 7 => 16 / 2 => 8 + 4 => 12
			// 0.5 int 0 / 1.5 int 1 / 2.5 int 2 / 3.5 int 3 => 0 + 1 + 2 + 3 + 4
			
		}catch(Exception e) {
				e.printStackTrace();
		}
	}
}

0개의 댓글