【问题标题】:Modifying Output in String Input By Text File (Java) [closed]通过文本文件(Java)修改字符串输入中的输出[关闭]
【发布时间】:2014-02-24 23:44:35
【问题描述】:

提前感谢大家。

我有几行通过文本文件输入的字符串,我想修改输出以删除每个字符串的最后两个字母。这是文本文件当前读取的内容:

你好,你好吗 酷
我很了不起

这是我正在使用的代码(来自 Java-tips.org)

package MyProject

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This program reads a text file line by line and print to the console. It uses
 * FileOutputStream to read the file.
 * 
 */

public class FileInput {

  public static void main(String[] args) {

File file = new File("MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
  fis = new FileInputStream(file);

  // Here BufferedInputStream is added for fast reading.
  bis = new BufferedInputStream(fis);
  dis = new DataInputStream(bis);

  // dis.available() returns 0 if the file does not have more lines.
  while (dis.available() != 0) {

  // this statement reads the line from the file and print it to
    // the console.
    System.out.println(dis.readLine());
  }

  // dispose all the resources after using them.
  fis.close();
  bis.close();
  dis.close();

} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}
  }

}

代码完美运行,但我想修改输出以删除每个字符串的最后两个字母(字符串 = 每行一个)谢谢大家!

【问题讨论】:

  • 我们不会为您编写程序。您向我们展示的只是您可以从文件中读取。请尝试修改文件中的字符串。
  • 我不明白你是怎么知道FileFileInputStreamBufferedInputStreamDataInputStream等的,但你不知道String。正如@Tdorno 所说,在要求我们为您做之前,您应该做更多的研究并自己尝试。

标签: java string text


【解决方案1】:

这是我的建议。不要将流用于如此琐碎和非负载密集型的事情。坚持基本原则,使用Scanner 并逐行阅读您的文件。

这是成功的方法!

  1. 了解如何使用 Scanner 从文本文件中逐行读取 Strings

  2. 确保将Stringsstr.split() 方法分开。

  3. 将每一行的String 值存储到数组/列表/表格中。

  4. 修改您存储的Strings 以删除最后两个字母。查看str.subString(s,f) 方法。

  5. 了解如何使用PrintWriter 将修改后的Strings 输出到文件中。

祝你好运!

评论回复
从 texfile 中以 String 的形式读入一行。

File file = new File("fileName.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
   String line = input.nextLine(); //<------This is a String representation of a line 
   System.out.println(line); //prints line
   //Do your splitting here of lines containing more than 1 word
   //Store your Strings here accordingly
   //----> Go on to nextLine
}

【讨论】:

  • @GeorgeTomlinson 啊,好点子。一秒钟!
  • 非常感谢!我一直在尝试使用扫描仪,发现这段代码最容易理解,尽管我不明白如何将每一行“转换”为字符串。我会知道我会使用以下内容进行修改: word = word.substring (0, word.length () - 2); // 删除第一个字符串中每个单词的最后两个字母,但除非我可以将该行转换为字符串,否则这不会有用:/
  • 我已经通过简单地添加: String word = dis.readLine();
  • @user3344206 很高兴我能帮上忙。如果您的问题已经解决,请随时接受这个作为答案。
  • 哈哈。 +1 表示积极的态度和似乎是好的建议。
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多