【问题标题】:My text reader program doesn't print anything我的文本阅读器程序不打印任何内容
【发布时间】:2013-01-01 12:33:45
【问题描述】:

我做了一个非常简单的文本阅读器只是为了测试机制,但它什么也没返回,我一无所知!我在 Java 方面不是很有经验,所以这可能是一个非常简单和愚蠢的错误!这是代码:

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

}

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;

}

}

【问题讨论】:

  • 只是提到“类名以大写字母开头”
  • “它什么也没返回,我一无所知”好吧,除非你给我们一些线索,否则你在运行程序时得到了什么。
  • Java 中的任何 IO 操作可能最好使用 commons-io (commons.apache.org/io/apidocs/org/apache/commons/io/…) 完成,除非您真的想自己学习如何操作。 :)
  • 字符串路径 = "C:/Test.txt";我认为应该是 "C:\\Test.txt";
  • 请不要将整个文件处理成String[]nOLReader() 通读整个文件以检查其长度是错误的;如果您确实需要将整个文件存储到数组中,请改用ArrayList&lt;String&gt;(动态调整大小)。

标签: java text io


【解决方案1】:

哇。这确实是大量工作,您只是为了读取文件。假设你想坚持你的代码,我会指出:

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

附:阅读一些简单的教程来了解 Java 中的 I/O。这是一些代码for your job

【讨论】:

  • 你能推荐一些教程吗?
  • @IDCaboutthename,如何向大师学习 Java?低头here
【解决方案2】:

您只从文件中读取一行,然后在永远循环中检查读取值(永远不会读取下一行,因此您永远不会在 cLine 中获得 null,因此循环永远不会结束)。将您的方法 nOLReader 更改为此(我在循环中添加了 cLine = 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;

}

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多