-1

Javaでファイルを読み込もうとしています。ファイルの構造は次のとおりです。

** <br/>
f=1100<br/>
d=111<br/>
e=1101<br/>
b=101<br/>
c=100<br/>
a=0<br/>
**

11001100110011001100110111011101110111011101110111011101100100100100100100100100100100100
101011011011011011011011011011011011011011111111111111111111111111111111111111111111111110
00000000000000000000000000000000000000000000

** で始まり、読みたいものがあります。** が再びあり、空白行とさらにデータがあります。データの読み方は知っているが、**の間だけのデータの読み方は扱えない

今まで私はこれをやった

 File toRead=new File("output.txt");
 FileInputStream fis=new FileInputStream(toRead);
 Scanner sc=new Scanner(fis);
 String currentLine;
 sc.delimiter = "**";
 while(sc.hasNext()){

     currentLine=sc.nextLine();
     system.out.println(sc.next());



  }
 fis.close();
4

3 に答える 3

3

これを試して :

File f = new File("output.txt");
    try {
        Scanner s = new Scanner(f);
        String line = "";
        while(s.hasNext()){
            line=s.nextLine();
            if(line.startsWith("**")){
                line=line.replaceAll("[**]", "");
                System.out.println(line);
                while((line=s.nextLine())!=null){  
                    if(!(line.endsWith("**")))
                        System.out.println(line);
                    else if(line.endsWith("**")){
                           line=line.replaceAll("[**]","");
                        System.out.println(line);
                        break;
                    }

                }
            } 
        }
    } catch (Exception ex) {

        System.out.println(ex.getMessage());
    }
于 2013-03-15T15:36:54.190 に答える
0

解析方法を尋ねているようです。構文解析は、プッシュ ダウン オートマトン (PDA) を基盤としています。真に汎用的なパーサーを実行するには、それを理解する必要があります。昔は lexx と yak を使ってパーサー用の C コードを生成していました。Javaにも似たようなものがあるかもしれません。

それがすべて失敗すると、パーサーをハードコーディングする必要があります。

while(sc.hasNext()){
 currentLine=sc.nextLine();
 system.out.println(sc.next());  //Great for debugging
 if(currentLine.equals("**") {   //use a constant instead
   newRecord = true;
   continue;
 } else if(currentLine.equals(???) {
   //set some values
 }  //etc

}

区切り文字は状態遷移を表し、コードでそれを追跡する必要があります...もちろん、これはPDAによるアドレスです。状態、トークン、および遷移を理解すると、はるかに簡単になります。

于 2013-03-15T15:30:04.700 に答える
0

あなたの場合、唯一の問題は、区切り文字を使用したいが、適切に配置しなかったことです。

File toRead=new File("output.txt");
FileInputStream fis=new FileInputStream(toRead);
Scanner sc=new Scanner(fis);
String currentLine;
sc.useDelimiter("\\*\\*");
while(sc.hasNext()){

 currentLine=sc.nextLine();
 System.out.println(sc.next());



 }
fis.close();

Regex で useDelimiter を呼び出す必要があり、* をエスケープする必要があります。だからあなたの正規表現は\*\*(それをエスケープするために * の前に\ 1つ)

useDelimiter は文字列を受け入れるため、 \ so をエスケープする必要があり\\ -> \ます\\*\\* -> \*\*

于 2013-03-15T15:52:15.020 に答える