2014-02-24 42 views
-4

感谢大家提前。通过文本文件(Java)修改字符串输入中的输出

字符串输入线通过一个文本文件,想修改输出到删除每个串的最后两个字母。这是文本文件中读取当前:

你好你怎么样 酷
我是惊人

,这是我使用(从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(); 
} 
    } 

} 

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

+3

我们不为您编写程序。你告诉我们的是你可以从文件中读入。请在文件中显示一些修改字符串的尝试。 – Tdorno

+1

我不明白你如何知道'File','FileInputStream','BufferedInputStream','DataInputStream'等等,但你不知道'String'。正如@Tdorno所说的,在要求我们为您做这件事之前,您应该自己做更多的研究和尝试。 –

回答

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 
} 
+0

@GeorgeTomlinson啊,好点。 1秒! – Tdorno

+0

谢谢吨!我一直在尝试扫描仪,并发现这个代码最容易理解,但我不明白我会如何将每行转换为字符串。我会知道我会使用以下来进行修改: word = word.substring(0,单词。length() - 2); //删除第一个字符串中每个单词的最后两个字母 但除非我可以将该行转换为字符串,否则这些字母不会有用:/ – user3344206

+0

我通过简单地添加:String word = dis来解决这个问题。的readLine(); – user3344206

相关问题