将数据从文本文件读入数组

时间:2013-12-03 08:32:40

标签: java arrays file-io

这是我的代码:

public static void main(String[] args) throws IOException 
{
    final int MAX_ARRAY_SIZE = 50;
    final String FILENAME = "Collection.txt";

    CDOutput out = new CDOutput();
    CDInput in = new CDInput();

    int count = 0;  // Counter to keep track of number of elements in the array
    int choice = 0; // Menu choice

    String[] songArray = new String[MAX_ARRAY_SIZE]; // Create array to hold song collection

    for (int i = 0; i <= MAX_ARRAY_SIZE; i++) // Fill array with empty objects
        songArray[i] = ""; 



    // Read the data from the input file into the array  -  THIS


    // Return the count for the elements currently in the array 



}

我正在阅读的文本文件看起来像这样(然后是Song,然后是逐行的艺术家):

Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss

如何将每一行分配到数组中?如果这太简单了,我很抱歉,因为我不熟悉Java。

2 个答案:

答案 0 :(得分:0)

您不需要发明轮子。您可以使用Apache FileUtils

Apache Commons IO

示例:

List<String> fileLines = FileUtils.readLines(new File("C:\test.txt"));

答案 1 :(得分:0)

试试这个,

public static void main(String[] args)
{
final int MAX_ARRAY_SIZE = 50;
final String FILENAME = "Collection.txt";

// CDOutput out = new CDOutput();
// CDInput in = new CDInput();

int count = 0; // Counter to keep track of number of elements in the
           // array
int choice = 0; // Menu choice

String[] songArray = new String[MAX_ARRAY_SIZE]; // Create array to hold
                         // song collection

BufferedReader br = null;

try
{

    String sCurrentLine;

    br = new BufferedReader(new FileReader("C:\\testing.txt"));
    int countA = 0;
    while ((sCurrentLine = br.readLine()) != null)
    {
    songArray[countA] = sCurrentLine;
    countA++;
    if (countA == MAX_ARRAY_SIZE)
    {
        break;
    }
    }

}
catch (IOException e)
{
    e.printStackTrace();
}
finally
{
    try
    {
    if (br != null)
        br.close();
    }
    catch (IOException ex)
    {
    ex.printStackTrace();
    }
}
for (int i = 0; i < MAX_ARRAY_SIZE; i++) 
    System.out.println(songArray[i]);


}

虽然我无法理解,使用out和in对象。