ITスクール DAY20 I/O stream

2023/08/07に公開

I/O Stream

データーを入力する時、出力する時の流れをStreamと呼ぶ。
javaのdate Streamは入力Streamは、入力のみ、出力Streamは、出力のみできるため、単方向ストリームともいえる。全てのデーターは、byte(to computer)に変換され、流れる。

streamは、大きく文字ストリーム(文字のみ),バイトストリームがある。
Reader, Writerは文字ストリーム, input,outputはバイトストリームで、
文字ストリームの場合も実際はbyte[]に変換されたり、自動的にencodingされたりする。

File Class

fileの情報を読んだり、削除することもできるクラス。
授業では、例外処理をしたが、一般例外である、I/O Exceptionで、
fileクラスの場合、読み取るファイルを入力しなくても例外は発生しない。

File file = new File(fileの経路)
public class FileEx1 {

public static void main(String[] args) {
   try {
   String fileName ="C:/soldeskjava/workspace/oopjava/src/oop20230807/data1.txt";
   File file = new File(fileName);
			
   if(file.exists()) { // fileの有無確認
   // fileの容量(byte)
  System.out.println(file.length() + "byte(s)");
 // file名
  System.out.println(file.getName());
 // fileの絶対経路
 System.out.println(file.getPath());
 // fileの削除
 file.delete();
	System.out.println("file is deleted.");
 } else {
	System.out.println("file isn't exist");
 }
			
 } catch (Exception e) {
	System.out.println("I/O fail : " + e);
	}
  }
}
44byte(s)
Scores.txt
C:\Users\gram\Desktop\Scores.txt
file is deleted.

Fileの内容コピー

今まで、Scannerクラスを使用するたび、コンストラクタのパラメーターに System.in を入力した。実は、System.in も一つずつ文字を読む入力ストリームであったのだ。
今回は、他のパラメータである、Fileクラスのオブジェクトをパラメータに入れ、Scannerを活用してみる。

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileEx2 {

public static void main(String[] args) throws Exception {
// ファイルをコピー : (原本)ファイルの内容を(コピー)ファイルをに保存
// (原本)ファイル : score.txt
// (コピー)ファイル: out.txt
		
 String fileName1 = "C:/Users/gram/Desktop/Scores.txt";
 String fileName2 = "C:/Users/gram/Desktop/out.txt";
		
 Scanner sc = new Scanner(new File(fileName1));
 PrintWriter pw = new PrintWriter(new File(fileName2));
		
 String str1 = ""; 	// sc.nextLine()のように文字を扱う変数		
 String str2 = "";	// 一つずつ文字を入れるための変数。
while(sc.hasNextLine()) {			
	str1 = sc.nextLine();
	int size = str1.length();
	str2 = "";
	
	for(int i=0; i <size; i++) {
		str2 += str1.charAt(i);
	  }			
	  System.out.println(str2); 	
	  pw.println(str2);			
	}
  sc.close();
  pw.close();
} // main() end

JOHN,100,80,80,85
YOHAN,95,50,100,60
MINSU,80,80,70,70
CHEN,50,60,50,50

一つのラインの文字をすべてstr2に入れ、また、次のラインをstr1に込め、str2で一文字ずつ入れる形だ。

Input

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;

public class InputEx1 {

public static void main(String[] args) {
		
  FileReader fr = null;
  BufferedReader br = null;
		
  try {
	String fileName = "C:/Users/gram/Desktop/Scores.txt";

	// 1) byte -> FileInputStream : 1byte
	
	
	FileInputStream fis = new FileInputStream(fileName);
			
	int data = 0;
	while(true) {
	   data = fis.read();
	   if(data == -1) {
		break;
	      }
	   System.out.println((char)data);
	} // while end
			
			
	// 2) char -> FileReader : 2byte
	
	fr = new FileReader(fileName);
	   data = 0;
	   while(true) {
	      data = fr.read();
	      if(data == -1) { break; }
	      System.out.println((char)data);
	    }
	
ì
²
 
ì
ˆ
˜
,
1
0
0
,
8
0
,
8
0
,
8
5
    // 3) enter
    
    fr = new FileReader(fileName);
    br = new BufferedReader(fr);
			
    String line = "";
	while(true) {
	  line = br.readLine();
	  if(line == null) { break; }
		System.out.println(line);
	    }
			
	} catch (Exception e) {
		System.out.println("파일 읽기 실패 : " + e);
   } finally {
 try {
	br.close();
	fr.close();
} catch(Exception e) { }
		}

  }

}

ButteredReaderは、文字単位ではなく、ライン単位で処理するため、スピードがとても速い。

Output

import java.io.FileWriter;
import java.io.PrintWriter;

public class OutputEx1 {

public static void main(String[] args) {
	 
	FileWriter fw = null;
	PrintWriter out = null;
		
	try {
	
	String fileName = "test.txt";
	// true : append
	// false : Overwrite
	fw = new FileWriter(fileName, false);
			
	// autoflush : true -> bufferclear
	out = new PrintWriter(fw, true);
	// プログラムのデーター --> txtで保管
			
	System.out.println("==print start==");
	out.println("홍길동,100,100,100");
    out.println("김길동,90,90,90");
	out.println("정길동,80,80,80");
	out.println("박길동,70,70,70");
	out.println("신길동,60,60,60");
	System.out.println(fileName + "에 성공적으로 저장완료 되었습니다.");
	} catch (Exception e) {
	    System.out.println("파일 쓰기 실패 : " + e);
	} finally {
	    try {
	out.close();
		fw.close();
	} catch(Exception e) { }
		}

	} // main() end

}
==print start==
test.txt에 성공적으로 저장완료 되었습니다. //print success

out
홍길동,100,100,100
김길동,90,90,90
정길동,80,80,80
박길동,70,70,70
신길동,60,60,60

Discussion