将数据从文件打印到数组 [英] Print data from file to array

查看:160
本文介绍了将数据从文件打印到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to have this file print to an array, not to screen.And yes, I MUST use an array - School Project - I'm very new to java so any help is appreciated. Any ideas? thanks

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();
            }
        }
    }
}


推荐答案

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

Nick, you just gave us the final piece of the puzzle. If you know the number of lines you will be reading, you can simply define an array of that length before you read the file

像......一样......

Something like...

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++;

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

Now that example's not going to mean much to be honest, so I did these two examples

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

The first one uses the concept suggested by Alex, which allows you to read an unknown number of lines from the file.

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

The only trip up is if the lines are separated by more the one line feed (ie there is a extra line between words)

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) {
        }
    }

}

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

The second demonstrates how to read the words into an array of known length. This is probably closer to the what you actually want

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) {
        }
    }

}

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

If you find either of these useful, I would appropriate it you would give me a small up-vote and check Alex's answer as correct, as it's his idea that I've adapted.

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

Now, if you're really paranoid about which line break to use, you can find the values used by the system via the System.getProperties().getProperty("line.separator") value.

这篇关于将数据从文件打印到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆