본문 바로가기
CLASS/JAVA

#15-3 / csv 데이터 저장

by eungSe__ 2024. 5. 22.

❗ csv 파일은 UTF-8 언어셋을 사용하지 않음 : EUC-KR로 변환 필요

   txt 파일 문서파일 외에 한글 깨짐이 발생할 경우 FileWriter(파일경로,언어셋,이어쓰기여부)

❗ csv 특성  : , 로 구분함 

⚡ csv 데이터 추가
//csv 데이터 저장
public class file20 {
	public static void main(String[] args) {
		new file_csv("member.csv"); //,쉼표 형태 csv여야 함
	}
}

//writer로 csv파일에 사용자 추가
class file_csv{
	String file_src = ""; //파일 위치 및 파일명
	File f = null;
	FileWriter fw = null;
	BufferedWriter bw = null;
	
	public file_csv(String url) { //즉시실행
		this.file_src = "D:\\webpage\\agree\\src\\main\\java\\io\\" + url;
		try {
			this.member_input(); //은닉화						
		}catch(Exception e) {
			
		}
	}
	
	private void member_input() throws IOException{ //사용자 추가 메소드(은닉화)
		this.f = new File(this.file_src);
		try {
			//FileWriter(파일경로,언어셋,이어쓰기여부)
			
			//this.fw = new FileWriter(this.f,true); //.csv파일에서 encoding 작살
			this.fw = new FileWriter(this.f, Charset.forName("EUC-KR"),false);
			this.bw = new BufferedWriter(this.fw); //메모리를 활성화 파일에 저장시킴
			ArrayList<String> mb = new ArrayList<String>();
			mb.add("유재석,ISFP"); // , : csv파일에서 자동 분리됨
			mb.add("강호동,ENFP");
			mb.add("안정환,INFP");
			mb.add("조정석,INTP");
			mb.add("차은우,ENTP");
			
			for(String m : mb) { //foreach로 해당 배열의 값을 csv파일에 저장
				this.bw.write(m + "\n"); //임시저장
				this.bw.flush(); //writer를 사용했으므로 flush로 메모리를 초기화
			}
			
		}catch(Exception e) {
			e.getMessage();
		}finally { 
			this.bw.close();
			this.fw.close();
		}
	}
}

 

⚡ csv 파일 로드
class file21_csv{
	String file_src = ""; //파일 위치 및 파일명
	File f = null;
	FileReader fr = null;
	BufferedReader br = null;
	
	public file21_csv(String url) throws Exception{
		this.file_src = "D:\\webpage\\agree\\src\\main\\java\\io\\" + url;
		this.file_csv_load();
	}
	
	private void file_csv_load() throws Exception{
		this.f = new File(this.file_src);
		
		try {
			//txt 외에 문서파일 기본 euc-kr로 언어셋 변환 후 출력
			this.fr = new FileReader(this.f, Charset.forName("euc-kr"));
			this.br = new BufferedReader(this.fr);
			
			String data = "";
			//해당 csv를 line별로 반목문을 이용해 출력
			while((data=this.br.readLine()) != null) { 
				System.out.println(data);
			}
					
			
		}catch(Exception e) {
			e.getMessage();
		}finally {
			this.br.close();
			this.fr.close();
		}
	}
}

 

⚡ 응용 (데이터 읽어서 => csv파일에 출력)
/*
 [응용문제]
 info.txt에 입력되어있는 데이터를 member.csv에 데이터를 입력시켜야 합니다.
 ,기준으로 각각의 데이터를 저장되도록 코드를 작성하시오.
 단 stream이든 writer 든 알아서~
 */
public class file22 {
	public static void main(String[] args) throws Exception{
		new file22_info();
	}
}

class file22_info{
	private String path = "D:\\webpage\\agree\\src\\main\\java\\io\\";
	private ArrayList<String> g_if = new ArrayList<String>();
	
	//읽기(Stream 사용해봄)
	private File f = null;
	private InputStream fis = null;
	private InputStreamReader isr = null;
	private BufferedReader bwr = null;
	
	//쓰기(Writer 사용해봄)
	private Writer fw = null;
	private BufferedWriter bw = null;
	
	//즉시실행 메소드
	public file22_info() throws Exception{
		this.getInfo(path + "info.txt");
	}
	
	//읽기
	private void getInfo(String a) throws Exception {
		this.f = new File(this.path);
		try {
			this.fis = new FileInputStream(a);
			this.isr = new InputStreamReader(fis);
			this.bwr = new BufferedReader(isr);
			
			String infodata = "";
			while((infodata=this.bwr.readLine()) != null) {
				this.g_if.add(infodata);
			}
			this.writeInfo(path + "member.csv");
			
		}catch(Exception e) {
			e.getMessage();
		}finally {
			this.bwr.close(); 
			this.bwr.close();
		}
	}
	
	//쓰기
	private void writeInfo(String a) throws Exception {
		this.fw = new FileWriter(a ,Charset.forName("EUC-KR"));
		this.bw = new BufferedWriter(fw);

		int w=0;
		while(w<this.g_if.size()) {
			this.bw.write(this.g_if.get(w) + "\n");
			this.bw.flush();
			
			w++; 
		}
		
		this.bw.close();
		this.fw.close();
	}
}

 

 

⚡ 응용 - 엑셀에서 데이터 출력
public class file1 {
	public static void main(String[] args) {
		new shop_data("d:\\shop_product.csv");
	}
}

class shop_data {
	String file_url = "";
	File f= null;
	public shop_data(String url) {
		this.file_url = url;
		this.shop_dataload();
	}
	
	public void shop_dataload(){
		this.f = new File(this.file_url); // ->여기서 바로 stream으로는 못넘어감
		try {
			//방법 01
			//InputStream is = new FileInputStream(this.f);
			//InputStreamReader isr = new InputStreamReader(is);
			//BufferedReader br = new BufferedReader(isr);
			
			FileReader fr = new FileReader(this.f,Charset.forName("euc-kr"));
			BufferedReader br = new BufferedReader(fr);
			br.readLine();
			
			ArrayList<ArrayList<String>> all = new ArrayList<ArrayList<String>>();
			ArrayList<String> datalist = null;
			
			Integer total_money = 0; //총 판매 금액
			String data = "";
			while((data=br.readLine())!= null) {
				String arr[] = data.split(","); //split으로 데이터를 구분하여 원시배열로 바꿈
				datalist = new ArrayList<String>();
				datalist.add(arr[0]);
				datalist.add(arr[3]);
				datalist.add(arr[5]);
				
				//각각의 오더별 수량 * 한개당 비용 
				int sum = Integer.parseInt(arr[3]) * Integer.parseInt(arr[5]);
				total_money += sum;
				
				String total = String.valueOf(sum);
				datalist.add(total);
				
				all.add(datalist);
			}
			System.out.println(all);
			
			// 금액에 , 찍기
			DecimalFormat df = new DecimalFormat("###,###");
			String moneys = df.format(total_money);
			
			System.out.println("총판매 금액 : "+ moneys + "원");
			
			br.close();
			fr.close();
			
		}catch(Exception e) {
			System.out.println("해당 파일을 로드하지 못했습니다.");
		}
	}
}

 

 

** PrintWriter : 

javascript 언어 때릴 수 있음(servlet 에서 많이 등장,순수 java에선 잘안씀) 
Writer의 자식 ( Object -> Writer -> PrintWriter )
문자 출력
FileWrite의 업그레이버전 이라고 보면됨

 

* servlet,spring : java->jsp로 출력시키는 경우 사용

PrintWriter (지금은몰라두댐)
public class file23 {

	public static void main(String[] args) {
		String url = "D:\\webpage\\agree\\src\\main\\java\\io\\info.txt";
		
		try {
			//파일을 로드하여 해당 내용을 기록하는 클래스
			PrintWriter pw = new PrintWriter(url);
			//pw.write("홍길동"); //true,false(덮어쓰기여부) 불가능 - 걍 초기화됨
			System.out.println(pw);
			
			pw.close();
		}catch(Exception e) {
			e.getMessage();
		}
		
	}

}

 

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

#16-2 / 서버 - TCP  (0) 2024.05.23
#16-1 / network 🔥  (0) 2024.05.23
#15-2 / StreamWriter,StreamReader  (0) 2024.05.22
#15-1 / 이미지(binary)  (0) 2024.05.22
#14-3 / Stream 활용법  (0) 2024.05.21