자바에서 문자열 토큰 중
글쓴이: 익명 사용자 / 작성시간: 금, 2018/05/04 - 11:25오후
number name age grade
1 Park 20 A\0
2 James 21 B\0
3 Kim 21\0
이러한 스트링을 각 number, name, age, grade 별로 토큰해서 따로 저장하고 싶은데
입력은 라인 단위로 받습니다.
처음에는
StringTokenizer tokens = new StringTokenizer(line(1~3)반복);
String number = tokens.nextToken("\t") ; // 이름
String name = tokens.nextToken("\t") ; // 나이
String age = tokens.nextToken("\t") ; // 성별
String grade = tokens.nextToken("\t") ; // 지역
System.out.println(p_label);
System.out.println(p_operator);
System.out.println(p_operand);
System.out.println(p_comment);이런식으로 짯는데 마지막 줄에는 grade에 값이 없어서 오류가 뜨네요.. 토큰하다가 null을 만나면 저절로 토큰이 종료될려면 어떻게 해야할까요??
Forums:

참고해보세요.
예제가 있어서. 작성해 봤습니다.
http://hunit.tistory.com/166
http://arer.tistory.com/48
https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
package project; import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String [] argv) throws IOException { //read File input = new File("input.txt"); FileReader fr = new FileReader(input); BufferedReader br = new BufferedReader(fr); //write File output = new File("output.txt"); FileWriter fw = new FileWriter(output); BufferedWriter bw = new BufferedWriter(fw); String text = ""; while(true) { String str = br.readLine(); if(str == null) { break; } text += str; System.out.println("파일에서 읽은 데이터 : "); System.out.println(str); bw.write(str+"\n"); } //예제 출처 //http://hunit.tistory.com/166 StringTokenizer str = new StringTokenizer(text, "\t"); int countTokens = str.countTokens(); for(int i=0; i<countTokens; i++) { String data = str.nextToken(); System.out.print("나눈 데이터 : "); System.out.println(data); } br.close(); fr.close(); bw.close(); fw.close(); } }//출력 결과
root@goorm:/workspace/test3# mkdir -p /workspace/test3/bin/ && javac -cp "$(find /workspace/test3/jar/ -name *.jar -printf %p:)" -d /workspace/test3/bin/ -g $(find /workspace/test3/src/ -name *.java) && java -Dfile.encoding=UTF-8 -cp "$(find /workspace/test3/jar/ -name *.jar -printf %p:)/workspace/test3/bin/" project/Main
파일에서 읽은 데이터 : number name age grade
파일에서 읽은 데이터 : 1 Park 20 A
파일에서 읽은 데이터 : 2 James 21 B
파일에서 읽은 데이터 : 3 Kim 21
나눈 데이터 : number name age grade
나눈 데이터 : 1
나눈 데이터 : Park
나눈 데이터 : 20
나눈 데이터 : A
나눈 데이터 : 2
나눈 데이터 : James
나눈 데이터 : 21
나눈 데이터 : B
나눈 데이터 : 3
나눈 데이터 : Kim
나눈 데이터 : 21
----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.
매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.
각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com
댓글 달기