자바에서 문자열 토큰 중

익명 사용자의 이미지

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을 만나면 저절로 토큰이 종료될려면 어떻게 해야할까요??

shint의 이미지

예제가 있어서. 작성해 봤습니다.
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

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.