2014-02-24 41 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

相關問題