如何只从.txt文件中有选择地读取数字和/或单词?

时间:2017-04-01 06:18:15

标签: java file linked-list fileinputstream

我有一个简单的 .txt文件(" theFile.txt"),格式如下,左栏是lineNumber,右栏是word

5     today
2     It's
1     "
4     sunny
3     a
6     "

对于此txt文件,我将两个单独的方法设置为每个 数字 < / strong>字符串,以及另一种扫描文件并将每个lineNumberword放入双链表DLL的方法:

  String fileName = "theFile.txt";

  public int getNumberOnly() {
       int lineNumber;

       //code to only get the lineNumber but NOT the words
       //This is as far as I got and I need help on this part

       return lineNumber;
  }

  public String getWordsOnly() {
       String words;

       //code to only get the words but NOT the lineNumber
       //This is as far as I got and I need help on this part

       return words;
  }

  public void readAndPrintWholeFile(String fileName){

          String fileContents = new String();
          File file = new File("theFile.txt");
          Scanner scanner = new Scanner(new FileInputStream(fileName));
          DLL<T> list = new DLL<T>();

         //Print each lineNumber and corresponding words for example
         // 5   Today
         // 2   It's

         while (scanner.hasNextLine())
         {
              fileContents = scanner.nextLine();
              System.out.println(list.getNumbersOnly() + " " +  list.getWordOnly());  
              //prints the lineNumber then space then the word
         }
  }

  //I already have all DLL accessors and mutators such as get & set next/previous nodes here, etc.

我一直坚持如何为getNumbersOnly()getWordOnly()

编写方法体的代码

我已尽力达到这一点。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

public static void readAndPrintWholeFile(String filename) throws FileNotFoundException {
    String fileContents;
    File file = new File(filename);
    Scanner scanner = new Scanner(new FileInputStream(file));
    Map<String, String> map = new HashMap<>();

    while (scanner.hasNextLine()) {
        try {
            fileContents = scanner.nextLine();
            String[] as = fileContents.split(" +");
            map.put(as[0], as[1]);
            System.out.println(as[0] + " " + as[1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            //If some problam with File formate e.g. number without word
        }
    }
}

你可以通过多种方式做到这一点,其中一个是听到的。 Hera我没有实现getNumberOnly()getWordsOnly()方法,我没有DLL实现,因此将数据放入mapHashMap)。

答案 1 :(得分:0)

你需要传递&#34; fileContents&#34;作为函数的参数。

public int getNumberOnly(String fileContents) {
   int lineNumber;
   //Get position of space
   int spacePos = fileContents.indexOf(" ");
   //Get substring from start till first space is encountered. Also trim off any leading or trailing spaces. Convert string to int via parseInt
   lineNumber = parseInt(fileContents.subString(0,spacePos).trim());
   return lineNumber;
}

public String getWordsOnly(String fileContents) {
   String words;
   int spacePos = fileContents.indexOf(" ");
   //Get substring from first space till the end
   words = fileContents.subString(spacePos).trim();
   return words;
}