FileReader
public static void m1() { File file = new File("c:\\storage", "m2.txt"); FileReader fr = null; try { fr = new FileReader(file); // File 입력 데이터 // 1. 1글자 : int // 2. 여러글자 : char[] // 1글자를 저장할 변수 int c; // read() 메소드 // 1. 읽은 문자를 반환 // 2. 모두 읽어서 읽은 문자가 없으면 -1 반환 // String str에 파일 내용 저장하기 StringBuilder sb = new StringBuilder(); while((c = fr.read()) != -1) { sb.append((char)c); } String str = sb.toString(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } }
FileReader
public static void m2() { File file = new File("c:\\storage", "m3.txt"); FileReader fr = null; try { fr = new FileReader(file); // 3글자를 저장할 배열 char[] cbuf = new char[5]; // read(char[] cbuf) 메소드 // 1. 읽은 글자는 cbuf 배열에 저장 // 2. 실제로 읽은 글자 수를 반환 // 3. 읽은 글자가 없으면 -1 반환 // m3.txt 파일 읽는 과정 // readCnt cbuf // 1 5 a p p l e // 2 5 \n m a n g // 3 2 o \n a n g // 4 -1 while(true) { int readCnt = fr.read(cbuf); if(readCnt == -1) { break; } for(int i = 0; i < readCnt; i++) { // 읽은 글자 수(readCnt)만큼 반복 System.out.print(cbuf[i]); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } }
m3.txt 읽어서 String str에 저장
File file = new File("C:\\storage", "m3.txt"); FileReader fr = null; try { fr = new FileReader(file); char[] cbuf = new char[5]; StringBuilder sb = new StringBuilder(); int readCnt; while((readCnt = fr.read(cbuf)) != -1) { sb.append(cbuf, 0, readCnt); } String str = sb.toString(); System.out.println(str); } catch(IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch(IOException e) { e.printStackTrace(); } } }
BufferedReader
File file = new File("C:\\storage", "m4.txt"); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(file); br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); String line = null; while((line = br.readLine()) != null) { sb.append(line + "\n"); } String str = sb.toString(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); } finally { try { if(br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } }
try-catch-resources문
try (BufferedReader br = new BufferedReader(new FileReader("c:\\storage\\m3.txt"))) { StringBuilder sb = new StringBuilder(); String line = null; while((line = br.readLine()) != null) { sb.append(line + "\n"); } String str = sb.toString(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); }
CSVReader
- Product 클래스
public class Product { private String number; private String name; private int price; public Product() { } public Product(String number, String name, int price) { super(); this.number = number; this.name = name; this.price = price; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Product [number=" + number + ", name=" + name + ", price=" + price + "]"; }
- CSVReader 클래스
public static void main(String[] args) { File file = new File("c:\\storage", "product.csv"); try(BufferedReader br = new BufferedReader(new FileReader(file))) { // 첫 행 읽어 버리기 br.readLine(); // 한 줄 읽어서 Product 객체 생성하고 ArrayList에 저장 List<Product> products = new ArrayList<Product>(); String line = null; while((line = br.readLine()) != null) { String[] arr = line.split(","); Product product = new Product(); product.setNumber(arr[0]); product.setName(arr[1]); product.setPrice(Integer.parseInt(arr[2])); products.add(product); } // ArrayList 확인 for(Product product : products) { System.out.println(product); } } catch(IOException e) { e.printStackTrace(); } } }
출력:
Product [number=100, name=새우깡, price=1500]
Product [number=101, name=양파링, price=2000]
Product [number=102, name=홈런볼, price=3000]
XMLReader
- Product 클래스
public class Product { private String number; private String name; private int price; public Product() { } public Product(String number, String name, int price) { super(); this.number = number; this.name = name; this.price = price; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Product [number=" + number + ", name=" + name + ", price=" + price + "]"; } }
- XMLReader클래스
public class XMLReader { public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File file = new File("C:\\storage", "product.xml"); Document document = builder.parse(file); // product.xml을 파싱(분석)한 document 객체 // 최상위 요소(root) Element root = document.getDocumentElement(); System.out.println("최상위 요소 : " + root.getNodeName()); // 최상위 요소의 자식 노드들 NodeList nodeList = root.getChildNodes(); for(int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); // 줄 바꾼(#text)과 <product>태그로 구성 if(node.getNodeType() == Node.ELEMENT_NODE) { // 노드가 Element인가?(줄바꿈 #text 제외되고 <product>태그만 남음) NodeList nodeList2 = node.getChildNodes(); // <product> 태그의 자식노드(줄바꿈 #text, <number>, <name>, <price> 태그) for(int j = 0; j < nodeList2.getLength(); j++) { Node node2 = nodeList2.item(j); if(node2.getNodeType() == Node.ELEMENT_NODE) { System.out.println(node2.getNodeName() + node2.getTextContent()); } } } } } catch (Exception e) { e.printStackTrace(); } } }
JSONReader
File file = new File("C:\\storage", "product.json"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { StringBuilder sb = new StringBuilder(); String line = null; while((line = br.readLine()) != null) { sb.append(line); } String str = sb.toString(); JSONArray arr = new JSONArray(str); List<Product> products = new ArrayList<Product>(); for(int i = 0, length = arr.length(); i < length; i++) { JSONObject obj = arr.getJSONObject(i); Product product = new Product(); product.setNumber(obj.getString("number")); product.setName(obj.getString("name")); product.setPrice(Integer.parseInt(obj.getString("price"))); } for(Product product : products) { System.out.println(product); } } catch(IOException e) { e.printStackTrace(); }