FIF's 코딩팩토리

자바 기초 NCS교육과정(40)-스트림 본문

Back-End/국비 NCS교과과정

자바 기초 NCS교육과정(40)-스트림

FIF 2019. 8. 1. 15:18
반응형
Stream

입출력 스트림


java.io.*; 패키지에서 제공한다.
   줄줄흐르다, 줄을지어 이어지다, 줄기, 개울, 시내


2 스트림 : 한 쪽에서 보내준 입력 데이터를 다른 한쪽으로
   출력하는 데이터의 흐름(순서가 있는 데이터의 흐름)

3 자바에서 스트림은 순서 있는 데이터의 일방적인 흐름


4 스트림 종류
   1) 입력/출력   
      입력 스트림 : InputStream, Reader(2바이트)
      출력 스트림 : OutputStream, Writer
      
   2)처리 단위로 구분
     바이트 스트림 : 바이트 , 배열바이트, 정수바이트
     문자 스트림 : 문자, 배열문자, 문자열

   3)기능에 따라
    데이터 싱크 스트림(데이터 전달 기능)-목적지에 직접연결        
     FileInput(Output)Stream, ByteArrayInput(Output)Stream
     데이터 처리 스트림(데이터의 조작 기능)-목적지에 간접연결
     BufferedInput(Output)Stream

 


   

Java159_stream.java

 

첫 앞글자만 나오는 코드

public class Java159_stream {

	public static void main(String[] args) {
		System.out.println("데이터 입력");
		
		//콘솔창 목적지에 InputStream으로 연결
		InputStream is =System.in;
		
		try {
			int line=is.read();//유니코드 int로 변환
			System.out.println((char)line);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

출력결과

 

Java160_stream.java   

 

각각의 단어가 개행으로 나오는 코드

public class Java160_stream {
	/*
	 * carriage return:줄의 처음으로 이동(13)
	 * line feed(다음 줄로 이동(10)
	 */
	public static void main(String[] args) {
		System.out.println("데이터 입력");
		InputStream is =System.in;
		
		int data;
		try {
			//1. is.read ()을 호출해서 문자를 읽어옴
			//2. read()에서 리턴해주는 문자를 data변수에 저장
			//3. data변수의 값과 13을 비교
			//4. while문의 조건식이 true이면 블록을 수행
		
			while((data=is.read())!=13) {
				System.out.println((char)data);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
			

	}

}

출력결과


Java161_stream.java 

 

입력한 데이터와 똑같이 나오는 코드

public class Java161_stream {

	public static void main(String[] args) {
		System.out.println("데이터 입력: ");
		
		//바이트 스트림
		InputStream is = System.in;
		//바이스트림과 문자스트림 연결
		InputStreamReader ir = new InputStreamReader(is);
		//문자스트림
		BufferedReader br=new BufferedReader(ir);
		
		try {
			//readLine():한 라인을 읽어와서 String 타입으로 리턴
			String line=br.readLine();
			System.out.println(line);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				//스트림 연결 종료
				br.close();
				ir.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		

	}

}

출력결과

 

 
Java162_stream.java   

public class Java162_stream {

	public static void main(String[] args) {
		// 바이트 스트림
		InputStream is = System.in;
		// 바이스트림과 문자스트림 연결
		InputStreamReader ir = new InputStreamReader(is);
		// 문자스트림
		BufferedReader br = new BufferedReader(ir);

		int x, y;

		try {
			System.out.print("x: ");
			x = Integer.parseInt(br.readLine());
			System.out.print("y: ");
			y=Integer.parseInt(br.readLine());
			System.out.printf("%d + %d = %d\n",x,y,x+y);
		} catch (NumberFormatException | IOException e) {
			e.printStackTrace();
		}finally {
			try {
				br.close();
				ir.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

출력결과

 

 

 

Java163_stream.java   

public class Java163_stream {

	public static void main(String[] args) {
		System.out.println("[순번 이름 평균]입력");
		Scanner sc = new Scanner(System.in);
		System.out.printf("순번:%d\n", sc.nextInt());
		System.out.printf("이름:%s\n", sc.next());
		System.out.printf("평균:%.1f\n", sc.nextDouble());
	}

}

출력결과

 

Java164_stream.java   

public class Java164_stream {

	public static void main(String[] args) {
		File file = new File("sample.txt");
		System.out.println(file.exists());
		System.out.println(file.isFile());
		System.out.println(file.length());
		System.out.println(file.canRead());

		FileWriter fw = null;
		try {
			//true : append, false : update 기본(false)
			fw = new FileWriter(file);
			fw.write("java\r\n");//buffer에 쓰여진다
			fw.write("jsp\r\n");
			fw.flush();//버퍼에 있는 내용을 작성한다.
			fw.write("spring");
			//fw.close();
			fw.write("oracle");//Error =>close 한 후에는 다시 객체생성 후에 작성이 가능하다.
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}

출력결과

 

Java165_stream.java   

public class Java165_stream {

	public static void main(String[] args) {
		File file = new File("sample.txt");
		FileReader fr = null;
		BufferedReader br = null;
		int data;

		try {// 한글자씩
			fr = new FileReader(file);
			// read() : 파일의 긑일때 -1을 리턴한다.
			while ((data = fr.read()) != -1) {
				System.out.print((char) data);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("//////////////////////////////////////////");
		try {// 한라인씩
			fr = new FileReader(file);
			br = new BufferedReader(fr);
			String line = "";
			// 파일의 끝이면 readLine()는 null을 리턴한다.
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("//////////////////////////////////////////");

		Scanner sc = null;
		try {
			sc = new Scanner(file);
			while (sc.hasNextLine()) {
				System.out.println(sc.nextLine());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally {
			sc.close();
		}

	}

}

출력결과

 

 

경로 : src/java1011_stream/score.txt 

score.txt

kim:56/78/12
hong:46/100/97
park:96/56/88


Java167_stream.java

public class Java167_stream {

	public static void main(String[] args) {
		File file=new File("src/java1011_stream/score.txt");
		RandomAccessFile raf=null;
		
		try {
			//"r":읽기(read)만 가능하다.
			//"rw":읽기(read) 쓰기(write)가 가능하다.
			raf=new RandomAccessFile(file,"r");
			//현재 포인터 위치 리턴
			System.out.println(raf.getFilePointer());//0
			System.out.println((char)raf.read());//k //유니코드값으로 읽음
			System.out.println(raf.getFilePointer());//1
			System.out.println(raf.readLine());//im:56/78/12
			String line=raf.readLine();//hong:46/100/97 14
			System.out.printf("%s %d\n",line,line.length());
			System.out.println(raf.getFilePointer());//30
			//포인터의 위치를 변경한다.(파일 처음부터 포인터를 찾는다)//0부터 4로 이동
			raf.seek(4);
			System.out.println(raf.getFilePointer());//4
			System.out.println(raf.readLine());//56/78/12
			//현재 포인터가 있는 위치를 기준으로 건너뛴다(-값 사용 불가)
			raf.skipBytes(2);
			System.out.println(raf.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

Java168_stream.java

public class Java168_stream {

	public static void main(String[] args) {
		File file=new File("src/java1011_stream/song.txt");
		RandomAccessFile raf=null;
		String stn= new String("\r\nMaron 5 - Daylight, Sunday Moring\r\n");
		try {
			raf=new RandomAccessFile(file, "rw");
			//song.txt파일의 총길이를 리턴한다.
			long size=raf.length();
			//파일의 끝으로 포인터를 이동한다.
			raf.seek(size);
			
			//파일에 문자열 추가
			raf.writeBytes(stn);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

위 코드를 실행하면 메모장의 내용이 추가된다.

내용 추가되기 전
내용 추가된 후

 

Java169_stream.java

public class Java169_stream {

	public static void main(String[] args) {
		File file = new File("src/java1011_stream/temp");
		if (!file.isDirectory()) {
			file.mkdirs();
		}

		System.out.println(file.isDirectory());
		System.out.println(file.isFile());

		file = new File("src/java1011_stream/song.txt");
		System.out.println(file.exists());

		file = new File("src/java1011_stream");
		String[] list = file.list();
		for (String sn : list)
			System.out.println(sn);
		System.out.println("//////////////////////////////////////////////////////////////////////////////////////");
		
		File[] listFile=file.listFiles();
		for(File fe:listFile) {
			if(fe.isFile())
				System.out.println(fe.getName());
		}
		
		file = new File("src/java1011_stream/source.txt");
		if(file.exists()) {
			file.delete();
			System.out.println(file.getName()+" 파일 삭제완료");
		}else {
			System.out.println(file.getName()+"파일 없음");
		}
	}

}

출력결과

 

 

javademo의 폴더와 파일 리스트를 출력

 

Java170_stream.java

public class Java170_stream {

	public static void main(String[] args) {
		File file = new File(".");
		System.out.println(file.getAbsoluteFile());
		System.out.println(file.getAbsolutePath());
		File[] listFile = file.listFiles();
		for (File sn : listFile)
			System.out.println(sn);	
	}
}

출력결과

 

 

Java171_stream.java

public class Java171_stream {

	public static void main(String[] args) {
		File file = new File("src/java1011_stream/prob.txt");
		if(!file.exists()) {
			try {
				file.createNewFile();
				System.out.println("파일 생성");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("Program end");
	}

}

 

Java173_stream.java

public class Java173_stream {

	public static void main(String[] args) {
		File file1 = new File("src/java1011_stream/song.txt");
		File file2 = new File("src/java1011_stream/score.txt");
		
		SequenceInputStream ss = null;
		FileInputStream fn1=null;
		FileInputStream fn2=null;
		try {
			fn1= new FileInputStream(file1);
			fn2= new FileInputStream(file2);
			
			//두개의 입력스트림을 연결해서 하나의 스트림처럼 읽어옴
			ss=new SequenceInputStream(fn1, fn2);
			int data;
			while((data=ss.read())!=-1) {
				System.out.print((char)data);
			}
					
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

텍스트 파일의 내용이 합쳐져서 출력

 

 

직렬화(Serializable)

  1 객체를 연속적인 데이터로 변환하는 것이다.


  2 객체의 멤버변수들의 값을 일렬로 나열하는 것이다.


  3 객체를 저장하기 위해서는 객체를 직렬화해야한다.


  4 객체를 저장한다는 것은 객체의 멤버변수의 값을 저장한다는 것이다.


  5 객체를 직렬화하여 입출력하는 스트림
   ObjectInputStream, ObjectOutputStream

 

Phone.java

public class Phone implements Serializable{//연속으로 저장
	String name;
	//직렬화에서 제외할 멤버변수에 transient 을 명시한다
	transient int price;

	public Phone() {

	}

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

	@Override
	public String toString() {
		return name + "\t" + price;
	}

}

 

Java174_stream.java

public class Java174_stream {

	public static void main(String[] args) {
		File file = new File("src/java1011_stream/phone.dat");
		FileOutputStream fs = null;
		ObjectOutputStream os = null;
		FileInputStream fi = null;
		ObjectInputStream oi = null;
		try {
			fs = new FileOutputStream(file);
			os = new ObjectOutputStream(fs);
			Phone p = new Phone("android", 5000);
			os.writeObject(p);
			os.writeObject(new String("java"));

			os.flush();
			System.out.println("객체 저장");
			// 객체를 저장하기 위해서는 직렬화되어있어야 한다
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			fi = new FileInputStream(file);
			oi = new ObjectInputStream(fi);
			Phone p = (Phone) oi.readObject();
			System.out.println(p.toString());
			String st = (String) oi.readObject();
			System.out.println(st.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

}

출력결과

 




    
      

     
     
     
     
     

반응형
Comments