将数据从文件打印到数组

时间:2012-08-24 05:20:25

标签: java arrays file io

我需要将此文件打印到数组,而不是屏幕。是的,我必须使用数组 - 学校项目 - 我对java很新,所以任何帮助都会受到赞赏。有任何想法吗?感谢

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class HangmanProject
{
    public static void main(String[] args) throws FileNotFoundException
    {

        String scoreKeeper;     // to keep track of score
        int guessesLeft;        // to keep track of guesses remaining
        String wordList[];    // array to store words


        Scanner keyboard = new Scanner(System.in);    // to read user's input

        System.out.println("Welcome to Hangman Project!");

        // Create a scanner to read the secret words file
        Scanner wordScan = null;

        try {
            wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
            while (wordScan.hasNext()) {
                System.out.println(wordScan.next());
            }
        } finally {
            if (wordScan != null) {
                wordScan.close();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您是否需要更多帮助来读取文件,或将String转换为已解析的数组?如果您可以将文件读入String,只需执行以下操作:

String[] words = readString.split("\n");

这会在每个换行符时拆分字符串,所以假设这是你的文本文件:

字1

字2

WORD3

单词将是:{word1,word2,word3}

答案 1 :(得分:1)

如果您正在阅读的单词存储在文件的每一行中,您可以使用hasNextLine()nextLine()一次读取一行文本。使用next()也可以,因为你只需要在数组中抛出一个单词,但nextLine()通常是首选。

至于仅使用数组,您有两个选择:

  • 您要么声明一个大数组,您确定的大小永远不会小于单词总数;
  • 你浏览文件两次,第一次读取元素数量,然后根据该值初始化数组,然后在你添加字符串时再次浏览它。

通常建议使用动态集合,例如ArrayList()。然后,您可以使用toArray()方法将列表转换为数组。

答案 2 :(得分:1)

尼克,你刚刚给了我们最后一块拼图。如果您知道要读取的行数,则可以在读取文件之前简单地定义该长度的数组

像...一样的东西。

String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
    wordArray[index] = word;
    index++;

现在这个例子并不意味着说实话,所以我做了这两个例子

第一个使用Alex建议的概念,它允许您从文件中读取未知数量的行。

唯一的旅行是如果线条被一个换行符分开(即单词之间有一条额外的行)

public static void readUnknownWords() {

    // Reference to the words file
    File words = new File("Words.txt");
    // Use a StringBuilder to buffer the content as it's read from the file
    StringBuilder sb = new StringBuilder(128);

    BufferedReader reader = null;
    try {

        // Create the reader.  A File reader would be just as fine in this
        // example, but hay ;)
        reader = new BufferedReader(new FileReader(words));
        // The read buffer to use to read data into
        char[] buffer = new char[1024];
        int bytesRead = -1;
        // Read the file to we get to the end
        while ((bytesRead = reader.read(buffer)) != -1) {

            // Append the results to the string builder
            sb.append(buffer, 0, bytesRead);

        }

        // Split the string builder into individal words by the line break
        String[] wordArray = sb.toString().split("\n");

        System.out.println("Read " + wordArray.length + " words");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }

}

第二部分演示了如何将单词读入已知长度的数组中。这可能更接近你真正想要的东西

public static void readKnownWords() 

    // This is just the same as the previous example, except we
    // know in advance the number of lines we will be reading    
    File words = new File("Words.txt");

    BufferedReader reader = null;
    try {

        // Create the word array of a known quantity
        // The quantity value could be defined as a constant
        // ie public static final int WORD_COUNT = 10;
        String[] wordArray = new String[10];

        reader = new BufferedReader(new FileReader(words));
        // Instead of reading to a char buffer, we are
        // going to take the easy route and read each line
        // straight into a String
        String text = null;
        // The current array index
        int index = 0;
        // Read the file till we reach the end
        // ps- my file had lots more words, so I put a limit
        // in the loop to prevent index out of bounds exceptions
        while ((text = reader.readLine()) != null && index < 10) {

            wordArray[index] = text;
            index++;

        }

        System.out.println("Read " + wordArray.length + " words");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }

}

如果你发现其中任何一个有用,我会认为你会给我一个小小的投票,并检查亚历克斯的答案是正确的,因为这是他的想法,我已经适应。

现在,如果你真的想要使用哪个换行符,你可以通过System.getProperties().getProperty("line.separator")值找到系统使用的值。