캠핑과 개발

자바파일쓰기 +1

java를 이용하여 텍스트 파일을 읽고 쓰는 예제입니다.

사용법은 매우 간단하지만 매번 찾아 보고 쓰게 되어 간단한 샘플을 포스팅합니다.


파일쓰기는 일반 텍스트형식과 바이너리 형식으로 쓰는 방법을 기록하며 순서는 다음과 같습니다.

1. 텍스트 파일 읽고 쓰기

2. 바이너리 파일 읽고 쓰기

3. 텍스트 파일 라인번호 읽기



1. 텍스트 파일 읽고 쓰기


  1. package test;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileReader;
  8. import java.io.FileWriter;
  9. import java.io.IOException;
  10.  
  11. public class FileTextWriteReadExample {
  12.    
  13.     public static void main(String[] args){
  14.        
  15.         File inFile = new File("C:\\Users\\Public""in.txt");
  16.         File outFile = new File("C:\\Users\\Public""in.txt");
  17.        
  18.         //==========================//
  19.         // 텍스트 파일 쓰기
  20.         //==========================//
  21.         BufferedWriter bw = null;
  22.         try {
  23.             bw = new BufferedWriter(new FileWriter(outFile));
  24.             bw.write("테스트 합니다.");
  25.             bw.newLine();
  26.             bw.write("테스트 합니다.1");
  27.             bw.flush();
  28.         } catch (IOException e) {
  29.             e.printStackTrace();
  30.         }finally {
  31.             if(bw != null) try {bw.close()} catch (IOException e) {}
  32.         }
  33.        
  34.         //==========================//
  35.         // 텍스트 파일 읽기
  36.         //==========================//
  37.         BufferedReader br = null;
  38.         try {
  39.             br = new BufferedReader(new FileReader(inFile));
  40.             String line;
  41.             while ((line = br.readLine()) != null) {
  42.                 System.out.println(line);
  43.             }
  44.         } catch (FileNotFoundException e) {
  45.             e.printStackTrace();
  46.         } catch (IOException e) {
  47.             e.printStackTrace();
  48.         }finally {
  49.             if(br != null) try {br.close()} catch (IOException e) {}
  50.         }
  51.     }
  52. }
  53.  


2. 바이너리 파일 읽기 쓰기

바이너리 파일은 알맞은 데이터형에 맞도록 쓰게되며 쓴 형식을 알지 못하면 읽는것 조차 힘듭니다.

규칙적인 형식으로 파일을 썼다면 DataInputStream객체의 available() 메서드를 이용하여 반복문으로 읽어들여서 처리할 수 있습니다.

소스 코드상에 48라인에 주석처리 되어 있습니다.


  1. package test;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.DataInputStream;
  6. import java.io.DataOutputStream;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileNotFoundException;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. public class FileBinaryWriteReadExample {
  14.  
  15.     public static void main(String[] args) {
  16.  
  17.         File inOutFile = new File("C:\\Users\\Public""in.bin");
  18.  
  19.         // ==========================//
  20.         // 바이너리 파일 쓰기
  21.         // ==========================//
  22.         DataOutputStream dos = null;
  23.         try {
  24.            
  25.             dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(inOutFile)));
  26.             dos.writeInt(1);
  27.             dos.writeUTF("안녕하세요");
  28.             dos.flush();
  29.        
  30.         } catch (IOException e) {
  31.             e.printStackTrace();
  32.         } finally {
  33.             if (dos != null) try { dos.close()} catch (IOException e) {}
  34.         }
  35.  
  36.         // ==========================//
  37.         // 바이너리 파일 쓰기
  38.         // ==========================//
  39.         DataInputStream dis = null;
  40.         try {
  41.            
  42.             dis = new DataInputStream(new BufferedInputStream(new FileInputStream(inOutFile)));
  43.            
  44.             System.out.println(dis.readInt());
  45.             System.out.println(dis.readUTF());
  46.            
  47.             /* 파일을 기록할 때 int 형식으로만 입력 한 경우 반복문을 통해서 읽는다.
  48.             while(dis.available() > 0){
  49.                 dis.readInt();
  50.             }*/
  51.            
  52.         } catch (FileNotFoundException e) {
  53.             e.printStackTrace();
  54.         } catch (IOException e) {
  55.             e.printStackTrace();
  56.         } finally {
  57.             if (dis != null) try {dis.close()} catch (IOException e) {}
  58.         } 
  59.     } 
  60. } 



3. 텍스트 파일 라인번호 읽기

이게 왜 필요한가 싶을지도 모르겠다. 그냥 lineCount 라는 변수를 하나 만들고 증가값을 1씩 증가하면 될텐데 말이다..

그래도 필요할지 모르니.. 일단 포스팅..


  1. package test;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.LineNumberReader;
  8.  
  9. public class FileLineNumberReaderExam {
  10.  
  11.     public static void main(String[] args) {
  12.         String path = "C:\\Users\\mjhwang\\Desktop";
  13.         String fileName = "test.txt";
  14.         LineNumberReader reader = null;
  15.         try {
  16.             reader = new LineNumberReader(new FileReader(new File(path, fileName)));
  17.             String line = null;
  18.             while ((line = reader.readLine()) != null){
  19.                 System.out.println("Line Number " + reader.getLineNumber() + " : " + line);
  20.             }
  21.         } catch (FileNotFoundException e) {
  22.             e.printStackTrace();
  23.         } catch (IOException e) {
  24.             e.printStackTrace();
  25.         }finally {
  26.             try{ if(reader != null) reader.close()}catch(IOException e){}
  27.         }
  28.     }
  29. }