简体   繁体   English

从文本文件读取的代码不起作用

[英]Code for reading from a text file doesn't work

I am new to Java and it has all been self-taught. 我是Java的新手,这一切都是自学成才的。 I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic. 我喜欢使用代码,但这只是一个爱好,因此,我没有关于该主题的任何正规教育。

I am at the point now where I am learning to read from a text file. 我现在正在学习从文本文件中读取内容。 The code that I have been given isn't correct. 我得到的代码不正确。 It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work. 当我对行的确切数目进行硬编码时,它可以工作,但是如果我使用“ for”循环来感测多少行,那么它将不起作用。

I have altered it a bit from what I was given. 我已经改变了我得到的东西。 Here is where I am now: 这是我现在的位置:

This is my main class 这是我的主班

package textfiles;

import java.io.IOException;

public class FileData {

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

    String file_name = "C:/Users/Desktop/test.txt";


        ReadFile file = new ReadFile(file_name);
        String[] aryLines = file.OpenFile();
        int nLines = file.readLines();
        int i = 0;            

    for (i = 0; i < nLines; i++) {
        System.out.println(aryLines[i]);
      }
    }    
  }

This is my class that will read the text file and sense the number of lines 这是我的课程,它将读取文本文件并感测行数

package textfiles;

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

public class ReadFile {

private String path;

public ReadFile(String file_path) {
    path = file_path;
}
int readLines() throws IOException {

  FileReader file_to_read = new FileReader(path);
  BufferedReader bf = new BufferedReader(file_to_read);

  int numberOfLines = 0;
  String aLine;

  while ((aLine = bf.readLine()) != null) {
  numberOfLines++;
}
bf.close();
return numberOfLines;
}

public String[] OpenFile() throws IOException {

  FileReader fr = new FileReader(path);
  BufferedReader textReader = new BufferedReader(fr);

  int numberOfLines = 0;

  String[] textData = new String[numberOfLines];

  int i;

 for (i = 0; i < numberOfLines; i++) {
    textData[i] = textReader.readLine();
  }

textReader.close();
return textData;
 }
}

Please, keep in mind that I am self-taught; 请记住我是自学成才的。 I may not indent correctly or I may make simple mistakes but don't be rude. 我可能没有正确缩进,也可能犯了简单的错误,但并不粗鲁。 Can someone look this over and see why it is not sensing the number of lines ( int numberOfLines ) and why it won't work unless I hardcode the number of lines in the readLines() method. 有人可以查看一下,看看它为什么不感知行数( int numberOfLines ),以及为什么除非我在readLines()方法中对行数进行硬编码,否则它不起作用。

The problem is, you set the number of lines to read as zero with int numberOfLines = 0; 问题是,您将int numberOfLines = 0;设置为零读取int numberOfLines = 0;

I'd rather suggest to use a list for the lines, and then convert it to an array. 我宁愿建议使用行列表,然后将其转换为数组。

public String[] OpenFile() throws IOException {

  FileReader fr = new FileReader(path);
  BufferedReader textReader = new BufferedReader(fr);

  //int numberOfLines = 0; //this is not needed

  List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file

  //this part should work akin to the readLines part
  String aLine;
  while ((aLine = bf.readLine()) != null) {
      textData.add(aLine); //add the line to the list
  }

  textReader.close();
  return textData.toArray(new String[textData.size()]); //convert it to an array, and return
 }
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];

textData is an empty array. textData是一个空数组。 The following for loop wont do anything. 下面的for循环不会做任何事情。

Note also that this is not the best way to read a file line by line. 还要注意,这不是逐行读取文件的最佳方法。 Here is a proper example on how to get the lines from a text file: 这是有关如何从文本文件获取行的正确示例:

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
   list.add(line);
}
br.close();

I also suggest that you read tutorials on object oriented concepts. 我还建议您阅读有关面向对象概念的教程。

This is a class that I wrote awhile back that I think you may find helpful. 这是我不久前写的一类,我认为您可能会有所帮助。

public class FileIO {
  static public String getContents(File aFile) {
    StringBuilder contents = new StringBuilder();
    try {
        //use buffering, reading one line at a time
        //FileReader always assumes default encoding is OK!
        BufferedReader input = new BufferedReader(new FileReader(aFile));
        try {
            String line = null; //not declared within while loop
            /*
             * readLine is a bit quirky :
             * it returns the content of a line MINUS the newline.
             * it returns null only for the END of the stream.
             * it returns an empty String if two newlines appear in a row.
             */
            while ((line = input.readLine()) != null) {
                contents.append(line);
                contents.append(System.getProperty("line.separator"));
            }
        } finally {
            input.close();
        }
    } catch (IOException ex) {
    }
    return contents.toString();
}

static public File OpenFile()
{
    return (FileIO.FileDialog("Open"));
}

static private File FileDialog(String buttonText) 
{
    String defaultDirectory = System.getProperty("user.dir");
    final JFileChooser jfc = new JFileChooser(defaultDirectory);
    jfc.setMultiSelectionEnabled(false);
    jfc.setApproveButtonText(buttonText);
    if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION) 
    {
        return (null);
    }
    File file = jfc.getSelectedFile();
    return (file);
}
}

It is used: 它用于:

File file = FileIO.OpenFile();

It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning. 它是专门为读取文件而设计的,因此希望可以成为学习中有用的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM