【问题标题】:How to load text file into string array with only import java.io.* and no other library如何仅使用 import java.io.* 而没有其他库将文本文件加载到字符串数组中
【发布时间】:2018-04-15 12:19:20
【问题描述】:

基本上我添加了“import java.util.Scanner”。但我希望我的代码在没有那个库的情况下也能工作,并且只有 "import java.io*" 。但是我希望我的文本文件中的所有单词(字典中的英语单词,在这种情况下总共有 109562 个单词)都在字符串数组中。因此,在这种情况下,没有扫描仪。怎么做?

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

public class tester{

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

    File f = new File("C:/Users/alienware14/Documents/words.txt");

    String [] words = new String [109562];

    readWords(f , words);



    /* 
     System.out.println("----ALL WORDS IN WORDS.TXT----");

     for(int i=0; i<words.length; i++){

     System.out.println("");
     System.out.print(words[i]);

     } */
  }


  public static String [] readWords(File f ,  String [] words) throws FileNotFoundException {

    Scanner s;
    s = new Scanner(f);

    for(int i = 0; i < words.length; i++){


      while (words[i] == null) {

        words[i] = s.next();

      }
    }

    s.close();

    return words;

  }
}

【问题讨论】:

  • 你试过什么?您是否在 Google 上搜索过“Java IO 教程”并阅读了一些内容?

标签: java file output load


【解决方案1】:

您可以使用java.io.FileReader 代替Scanner。只需谷歌“Java 读取文件”即可找到它的示例(使用扫描仪读取文件非常奇特)。虽然我真的不明白为什么您在导入扫描仪时遇到问题。听起来像家庭作业..

【讨论】:

    【解决方案2】:

    尝试拆分方法 String[] words = yourtext.split(" "); //分词方法中的用户空间

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 2015-04-05
      • 2021-12-13
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2016-06-14
      相关资源
      最近更新 更多