从文本文件中标记数据

时间:2016-03-06 05:45:02

标签: java io bufferedreader

我有一个

的文本文件
  

1

     

2

     

3

     

4

我正在尝试将每行数据标记为数组。但是,令牌[0]正在读取1 2 3 4.如何以

的方式制作它
tokens[0] = 1

tokens[1] = 2;

tokens[2] = 3;

我的代码基本上有什么问题。

  public static void readFile()
    {

        BufferedReader fileIn;

        String[] tokens;
        String inputLine;

        try 
        {
            fileIn = new BufferedReader(new FileReader("test.txt"));
            inputLine = fileIn.readLine();

            while (inputLine != null) 
            {
              tokens = inputLine.trim().split("\\s+");

              System.out.println(tokens[0]);
              inputLine = fileIn.readLine();



            }
            fileIn.close();
        }

        catch (IOException ioe) 
        {
            System.out.println("ERROR: Could not open file.");
            System.out.println(ioe.getMessage());
        }    
    }
}

3 个答案:

答案 0 :(得分:1)

我认为您的问题是您使用令牌数组的方式。

使用ArrayList作为NullOverFlow建议将提供您想要的行为。

这是使用ArrayList的快速解决方案,而Raghu K Nair建议采用整行而不是拆分。它是完整的 - 您可以自己运行以验证:

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

public class tokenize
{
    public static List<String> readFile( String fileName )
    {
        FileInputStream fileStrm = null;
        InputStreamReader reader = null;
        BufferedReader buffReader = null;
        List<String> tokens = null;
        try
        {
            // Set up buffered reader to read file stream.
            fileStrm = new FileInputStream( fileName );
            reader = new InputStreamReader( fileStrm );
            buffReader = new BufferedReader( reader );
            // Line buffer.
            String line;
            // List to store results.
            tokens = new ArrayList<String>(); 

            // Get first line.
            line = buffReader.readLine();
            while( line != null )
            {
                // Add this line to the List.
                tokens.add( line );
                // Get the next line.
                line = buffReader.readLine();
            }
        }
        catch( IOException e )
        {
            // Handle exception and clean up.
            if ( fileStrm != null )
            {
                try { fileStrm.close(); }
                catch( IOException e2 ) { }
            }
        }
        return tokens;
    }

    public static void main( String[] args )
    {
        List<String> tokens = readFile( "foo.txt" );
        // You can use a for each loop to iterate through the List.
        for( String tok : tokens )
        {
            System.out.println( tok );
        }
    }
}

这取决于您问题中描述的格式化的文本文件。

答案 1 :(得分:0)

我认为这可能会解决您的问题

public static void readFile() {

    try {
        List<String> tokens = new ArrayList<>();
        Scanner scanner;
        scanner = new Scanner(new File("test.txt"));
        scanner.useDelimiter(",|\r\n");
        while (scanner.hasNext()) {
            tokens.add(scanner.next());
            System.out.println(tokens);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MaxByTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

答案 2 :(得分:0)

我建议使用ArrayList来处理这个问题,如果你愿意,你可以随时将它转换为字符串数组:

String[]

试试这个:

    public void readFromFile(String path) {

    File file = new File(path);

    ArrayList<String[]> tokens = new ArrayList<String[]>(); //The reason why we store an array of strings is only because of the split method below.
    //also, why are you using split? if i were you i would totally avoid using split at all. if that is the case then you should change the above arrayList to this:
    //ArrayList<String> tokens = new ArrayList<String>();

    String inputLine; //the line to be read

    try (BufferedReader br = new BufferedReader(new FileReader(file))) { //use the "enhanced" try-catch that way you don't have to worry about closing the stream yourself. 

        while ((inputLine = br.readLine()) != null) { //check line
            tokens.add(inputLine.trim().split("\\s+")); //put in the above arraylist
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


    //Testing
    for (String[] token : tokens) {
        System.out.println(Arrays.toString(token));
    }

}