2013-01-01 95 views
0

我制作了一个非常简单的文本阅读器来测试机制,但它什么都没有返回,我很无能!我对Java不是很有经验,所以它可能是一个非常简单而愚蠢的错误!这里是代码:我的文本阅读器程序不打印任何东西

CLASS 1

import java.io.IOException; 

public class display { 


public static void main(String[] args)throws IOException { 

    String path = "C:/Test.txt"; 
    try{ 
    read ro = new read(path); 
    String[] fileData = ro.reader(); 
    for(int i = 0; i<fileData.length;i++){ 
     System.out.println(fileData[i]); 
    } 
    }catch(IOException e){ 
     System.out.println("The file specified could not be found!"); 
    } 
     System.exit(0); 
} 

} 

CLASS 2

import java.io.IOException; 
import java.io.FileReader; 
import java.io.BufferedReader; 

public class read { 

private String path; 

public read(String file_path){ 
    path = file_path; 
} 

public String[] reader() throws IOException{ 
    FileReader fR = new FileReader(path); 
    BufferedReader bR = new BufferedReader(fR); 

    int nOL = nOLReader(); 
    String[] textData = new String[nOL]; 
    for(int i = 0; i < nOL; i++){ 
     textData[i] = bR.readLine(); 
    } 
    bR.close(); 
    return textData; 

} 

int nOLReader()throws IOException{ 
    FileReader fR = new FileReader(path); 
    BufferedReader bR = new BufferedReader(fR); 
    String cLine = bR.readLine(); 
    int nOL = 0; 
    while(cLine != null){ 
     nOL++; 
    } 
    bR.close(); 

    return nOL; 

} 

} 
+3

只要提及“班级名称以大写字母开头” – Abubakkar

+1

“它什么都不返回,我无能为力”,除非您在运行程序时给我们一些线索,否则我们也无能为力。 – Abubakkar

+2

除非你真的想学习如何做,否则在java中的任何IO操作可能会更好地用commons-io完成(http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html)它自己。 :) –

回答

2

哇。这真的是很多工作你正在做的只是读取文件。假设yourelaly要坚持你的代码,我就指出:

在2级,

String cLine = bR.readLine(); 
int nOL = 0; 
while(cLine != null) { 
    nOL++; 
} 

将运行到一个无限循环,因为你永远读另一行,就在第一时间为所有。所以做成这样的:

String cLine = bR.readLine(); 
int nOL = 0; 
while(cLine != null) { 
    nOL++; 
    cLine = bR.readLine(); 
} 

P.S.阅读一些简单的教程,以了解Java中的I/O点。这里有一些代码for your job

+0

你能推荐任何教程吗? –

+1

查看http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html。 – fgb

+1

@IDCaboutthename,如何从主人那里学习Java?只要向下[在这里](http://docs.oracle.com/javase/tutorial/)。 – varevarao

0

您可以从文件中读取只有一条线,然后永远循环退房读值(下一行从来没有读过这么你永远不会在cLine中获得null,所以循环永远不会结束)。你的方法nOLReader改成这样(我加克莱恩= bR.readLine();在环路),它会工作:

int nOLReader() throws IOException { 
    FileReader fR = new FileReader(path); 
    BufferedReader bR = new BufferedReader(fR); 
    String cLine = bR.readLine(); 
    int nOL = 0; 
    while (cLine != null) { 
     nOL++; 
     cLine = bR.readLine(); 
    } 
    bR.close(); 
    return nOL; 

}