질문
현재 자바공부중인 전산과 학생입니다.
아직 초보라서 모르는것이 많이 있는데 몇일간 고민해도 답이 안나와서 질문을드립니다.
그럼 본격적인 질문들어가겠습니다.
잘 이해하셔서 간단한 코드 부탁드립니다.
Book.txt 라는 텍스트 파일이 있습니다.
그안에는 한 100건의 책 정보들이 들어있습니다. 그리고 이 파일을 읽습니다.
위치가 일정하진 Book-code: 00004959 라는 것도 포함되있습니다. 100건의 정보가 있으니 100건 있겠죠
Book-code: xxxxxxxx 이런씩으로 8자리로 되어 있구요 넘버도 마구섞여 있습니다.
이 Book-code를 찾아서 뒤의 xxxxxxxx의 숫자를 00000001 ~ 00000100 까지 순서대로 치환해서
Books.txt에 생성하고 싶습니다.
요약하자면 Book-code를 검색해서 그 뒤의 숫자 xxxxxxxx을 순서대로 바꿔서 새로운 파일로 생성
하고싶은것입니다. 쉽게말해서 자동으로 찾아 바꾸기 기능을 만들고 싶다는가죠
IndexOF인가 사용해서 Book-code를 찾긴해도 숫자를 바꿔서 새로운 파일에 만드는게 좀 ㅠ
소드도 함께 빠른 답변 부탁드릴게요 ㅠ
답변:
public static void main(String[] args) throws IOException { String fileName = "book.txt"; // 읽어올 파일명 File bookFile = new File("c:/", fileName); FileInputStream fis = new FileInputStream(bookFile); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); Hashtable table = new Hashtable(); String readLine = ""; // 파일 읽기 시작 while(true) { readLine = br.readLine(); // 한줄을 읽는다. if(readLine == null) { break; // 더이상 읽을게 없으면 종료 } // Book-Code의 위치를 찾습니다. int bookIndex = readLine.indexOf("Book-code:")+"Book-code:".length(); // Code 값을 Key로 설정 합니다. String key = readLine.substring(bookIndex, bookIndex+8).trim(); // HashTable에 Code 값 = Key , 라인 = Value 로 저장 table.put(key, readLine); } // 읽은 파이프는 모두 닫습니다. br.close(); fis.close(); // key 값 정렬을 위해 KeySet을 리스트로 변환합니다. List list = new ArrayList(table.keySet()); // key 값을 정렬합니다. Collections.sort(list); // 정렬된 키값으로 다시 출력합니다. FileOutputStream fos = new FileOutputStream(new File("c:/", fileName)); PrintWriter pw = new PrintWriter(fos, true); for (Object object : list) { pw.write(table.get(object)+"\n"); } pw.flush(); pw.close(); fos.close(); }