2017-04-10 61 views
1

我有一个大的文本文件,我想要阅读它,当我尝试做它没有任何操作,如从该文件中添加一些文本列出它的读取文件最大为一分钟,但是当我尝试添加一些文本到arrayList和接下来我想做一些操作它太慢了,你知道我怎么读取这些数据并使用它? 这是我的代码:如何阅读大文本文件,并在Java中使用它

public class ReaderTEst { 
public static void main(String[] args) throws IOException { 
    List<String> graphList = new ArrayList<>(); 
    List<String> edgeList = new ArrayList<>(); 
    FileInputStream inputStream = null; 
    Scanner sc = null; 
    try { 
     inputStream = new FileInputStream("myText.txt"); 
     sc = new Scanner(inputStream, "UTF-8"); 
     while (sc.hasNextLine()) { 
      String line = sc.nextLine(); 
      line = line.replace("\uFEFF", "");//i use UTF-8 file so I need delete unneeded character 
      if (Character.isWhitespace(line.charAt(0))) { 
       edgeList.add(line.trim()); 
      } else { 
       graphList.add(line); 
      } 
     } 
     if (sc.ioException() != null) { 
      throw sc.ioException(); 
     } 
    } finally { 
     if (inputStream != null) { 
      inputStream.close(); 
     } 
     if (sc != null) { 
      sc.close(); 
     } 
    } 
} 

} 它需要很多的时间,你知道它是如何可能会更快?我有600 MB 文件TXT当我改变:

List<Integer> graphList = new ArrayList<>(1); 
int i = 0; 
while (sc.hasNextLine()) {`String line = sc.nextLine();` 
     line = line.replace("\uFEFF", "");//i use UTF-8 file so I need delete unneeded character 

      graphList.add(i++); 

    } 

我的作品,但是当我想要把字符串时间太长的时间

回答

0

你的主要问题如下:

List<String> graphList = new ArrayList<>(); 
List<String> edgeList = new ArrayList<>(); 

您应该使用初始容量初始化每个List,以便JVM不需要自动扩展后备阵列。

line = line.replace("\uFEFF", ""); 

这也会减慢你的程序。 \uFEFF每隔多久一次?在尝试更换之前,我会检查该行是否包含\uFEFF

除此之外,没有其他优化;也许你可以利用FileChannel来读取文件,但这就是它。

1

您应该使用BufferedReader.readLine()。你可以阅读每秒数百万行。 Scanner对于你正在做的事情来说是过火。

但是\uFEFF不是文字。这是真的一个文本文件?这是一个BOM标记吗?在这种情况下,它只会在第一行的开头:不需要在每行中扫描它。

+0

这是正弦波我使用UTF-8和第一个字符我有奇怪的空字符,所以我尽量只的charAt(0) – grapexs

+0

所以用它它*是一个BOM标记,所以你应该只从第一行删除它。 – EJP

0

首先我建议使用列表的LinkedList实现,因为架构特性。因此,ArrayList是建立在数组上的,LinkedList由Nodes组成。 ArrayList创建新的更大的数组,然后将旧的数组复制到新的数组中,然后达到一定的容量。 Oracle有这个完美的文档,我把它推荐给你LinkedList ArrayList