1

入力ファイル a.txt にいくつかのコンテンツがあります

Line 1 : "abcdefghijk001mnopqr hellohello"
Line 2 : "qwertyuiop002asdfgh welcometologic"
Line 3 : "iamworkingherefromnowhere002yes somethingsomething"
Line 4 : "thiswillbesolved001here ithink"

a.txt ファイルを読み取って、2 つの別々のファイルに書き込む必要があります。つまり、001 を持つ行は output1.txt に、002 を持つ行は output2.txt に書き込む必要があります。

誰かがJavaプログラミングのロジックでこれを手伝ってくれますか?

ありがとう、ナレン

4

3 に答える 3

2
BufferedReader br = new BufferedReader( new FileReader( "a.txt" ));
String line;
while(( line = br.readLine()) != null ) {
    if( line.contains( "001" )) sendToFile001( line );
    if( line.contains( "002" )) sendToFile002( line );
}
br.close();

メソッド sendToFile001() および sendToFile002() は、次のようにパラメーター行を書き込みます。

ps001.println( line );

タイプ PrintStream の ps001 と ps002 で、前に開かれました (コンストラクターで?)

于 2012-12-17T17:35:39.307 に答える
0

Java を使用してテキスト ファイルを読み書きし、条件を確認して次のことを行う良い例を次に示します。

while ((line = reader.readLine()) != null) {
    //process each line in some way
    if(line.contains("001") {
     fileWriter1.write(line);  
    } else if (line.contains("002") ) {
     fileWriter2.write(line);    
    }
  } 
于 2012-12-17T17:31:47.970 に答える
0

コード完成。

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;

/**
 *
 * @author andy
 */
public class JFile {

    /**
     * @param args the command line arguments
     */

    static File master = null,
                m1     = null, // file output with "001"
                m2     = null; // file output with "002"

    static FileWriter fw1,
                      fw2;

    static FileReader fr = null;
    static BufferedReader br = null;

    public static void main(String[] args) throws FileNotFoundException, IOException
    {

         String root = System.getProperty("user.dir") + "/src/files/";

         master = new File ( root + "master.txt" );
         m1     = new File ( root + "m1.txt");
         m2     = new File ( root + "m2.txt");

         fw1     = new FileWriter(m1, true);
         fw2     = new FileWriter(m2, true);


         fr = new FileReader (master);
         br = new BufferedReader(fr);

         String line;
         while((line = br.readLine())!=null)
         {
             if(line.contains("001")) 
             {               
                 fw1.write(line + "\n");

             } else if (line.contains("002"))
             {
                 fw2.write(line + "\n");

             }
         }

         fw1.close();
         fw2.close();
         br.close();
    }

}

プロジェクト Netbeans : http://www.mediafire.com/?yjdtxj2gh785cyd

于 2012-12-17T17:53:42.280 に答える