2011-03-11 114 views
3

填充它,我想创建一个数组,填充它,而从格式化,像这样一个.txt文件中读取内容:创建一个数组由.TXT元素

item1 
item2 
item3 

所以最终的结果必须像一个数组这个:

String[] myArray = {item1, item2, item3} 

在此先感谢。

+0

看看这个答案http://stackoverflow.com/questions/4717838/text-file-parsing-using-java-suggestions-needed-on-which-one-to-use/4717928# 4717928 ...这是否足够? – CoolBeans 2011-03-11 20:41:27

回答

2
  1. FileReader,这样就可以轻松地阅读文件的每一行围绕BufferedReader;
  2. 将行存储在List(假设您不知道要读取多少行);
  3. 使用toArrayList转换为数组。

简单实现:

public static void main(String[] args) throws IOException { 
    List<String> lines = new ArrayList<String>(); 
    BufferedReader reader = null; 
    try { 
     reader = new BufferedReader(new FileReader("file.txt")); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      lines.add(line); 
     } 
    } finally { 
     reader.close(); 
    } 
    String[] array = lines.toArray(); 
} 
+0

这正是我需要的! :) – Franky 2011-03-11 21:10:30

1

这气味像功课。如果是这样,你应该重新阅读你的笔记,并告诉我们你已经尝试了什么。

个人而言,我会使用扫描仪(来自java.util)。

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

public class Franky { 
    public static void main(String[] args) { 
     Scanner sc = new Scanner(new File("myfile.txt")); 
     String[] items = new String[3]; // use ArrayList if you don't know how many 
     int i = 0; 
     while(sc.hasNextLine() && i < items.length) { 
      items[i] = sc.nextLine(); 
      i++; 
     } 
    } 

} 
相关问题