简体   繁体   English

程序仅读取.txt文件java中的最后一行

[英]program only read last line in .txt file java

I have a problem and don't know what to do. 我有问题,不知道该怎么办。 This method is supposed to read all the text in a .txt document. 该方法应该读取.txt文档中的所有文本。 My problem is when the document contains more then one line of text and the program only read the last line. 我的问题是,当文档包含多行文本时,程序仅读取最后一行。 The program don't need to worry about signs like . 该程序无需担心诸如的迹象。 , : or spaces, but it have to read all the letters. ,:或空格,但必须阅读所有字母。 Can anybody help me? 有谁能够帮助我?

example text 示例文字

hello my name is (returns the right result) 你好我的名字是(返回正确的结果)

hello my 你好我的

name is 名字是

(returns only name is) (仅返回名称为)

private Scanner x;
String readFile(String fileName)
{
  try {
    x = new Scanner (new File(fileName + (".txt")));
  }
  catch (Exception e) {
    System.out.println("cant open file");
  }
  while (x.hasNext()) {
    read = x.next(); 
  } 
  return read;
}

It's because when you use read = x.next() , the string in the read object is always being replaced by the text in the next line of the file. 这是因为当您使用read = x.next()read对象中的字符串始终被文件下一行中的文本替换。 Use read += x.next() or read = read.concat(x.next()); 使用read += x.next()read = read.concat(x.next()); instead. 代替。

You replace every read with every read() . 您可以将每个read替换为每个read() Also, you didn't close() your Scanner . 另外,您没有close() Scanner I would use a try-with-resources and something like, 我会使用“ try-with-resources类的方法,

String readFile(String fileName)
{
  String read = "";
  try (Scanner x = new Scanner (new File(fileName + (".txt")));) {
    while (x.hasNextLine()) {
      read += x.nextLine() + System.lineSeparator(); // <-- +=
    } 
  } catch (Exception e) {
    System.out.println("cant open file");
  }
  return read;
}

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

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