如何在java中使用scanner类

时间:2014-06-12 11:35:30

标签: java

我想将包含人名(Stringnames.rtf = ("ABHISHEK","ANKIT",........"ASHISH"))的names.rtf文件转换为单个String[]名称,以便name={"ABHISHEK","ANKIT",......"ASHISH"}

以下是我的代码建议。

import java.io.*;
import java.util.Scanner; 

 public class FileScan {
   public static void main(String[] args) throws IOException {

        Scanner s = null;
        String thestring ="";
        try {
            s = new Scanner(new BufferedReader(new FileReader("/Users/abhishekkumar/Desktop/names1.rtf")));
            while (s.hasNextLine()) {
                thestring+=(s.nextLine());                  
                thestring+="\n";
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }
        System.out.println(thestring);
    } 
   }

1 个答案:

答案 0 :(得分:-1)

首先,为什么用这种方式使用scanner类使用bufferedReader,fileReader等来读取文件?使用: -

File file = new File("filename.fileformat");
Scanner scanner = new Scanner(file);

在评论中查看文件的可能解决方案是: -

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        // Location of file to read
        File file = new File("data.rtf");
        String line="";
        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                line = scanner.nextLine();
                //System.out.println(line);


            }


          String[] nameArray=line.split(","); 

          for(String s:nameArray){

         System.out.print(s+" "); //parse the array to verify entries

         }

            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}