2013년 9월 6일 금요일

자바에서 파일의 특정 라인에 문자열 삽입하기 , 오라클자바커뮤니티,오라클자바교육,오라클자바강좌

자바에서 파일의 특정 라인에 문자열 삽입하기 , 오라클자바커뮤니티,오라클자바교육,오라클자바강좌

import java.io.*;


public class InsertLineToFile {

       
        public void insertStringInFile(File inFile, int lineno,
                        String lineToBeInserted) throws Exception {
               
                //파일에서 읽은 한라인을 저장하는 임시변수
                String thisLine = "";
               
                // 임시파일을 만듭니다.
                File outFile = new File("$$$$$$$$.tmp");

                // 아규먼트로 받은 입력 파일
                FileInputStream fis = new FileInputStream(inFile);
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));

                // output 파일
                FileOutputStream fos = new FileOutputStream(outFile);
                PrintWriter out = new PrintWriter(fos);
       
                int i = 1;
               
                //파일 내용을 한라인씩 읽어 삽입될 라인이 오면 문자열을 삽입
                while ((thisLine = in.readLine()) != null) {
                        if (i == lineno)
                                out.println(lineToBeInserted);
                        out.println(thisLine);
                        i++;
                }
                out.flush();
                out.close();
                in.close();

                inFile.delete();

                //임시파일을 원래 파일명으로 변경
                outFile.renameTo(inFile);
               
                System.out.println("INSERT OK~~~");
        }

        public static void main(String args[]) {
                try {
                        InsertLineToFile i = new InsertLineToFile();
                        i.insertStringInFile(new File(args[0]), Integer.parseInt(args[1]),args[2]);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}


[실행]
test.txt의 9라인에 "hello world"를 삽입....
java InsertLineToFile test.txt 9 "hello world"

오라클자바커뮤니티 실무 추천 강좌 -  개인80% 환급


댓글 없음:

댓글 쓰기