尝试逐行读取文本并在Java中的每一行写入输出文件

时间:2015-04-06 03:10:28

标签: java

我正在尝试从文本文件中读取数据(逐行),我想在输出文件中写入从苍蝇中读取的行。

以下是我编写代码的方法:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class read {

    public static void main(String args[])
    {
        String input = null;
        input = readFile();
        writeFile(input);

    }
    public static void writeFile(String in)
    {
        String fileName = "output.txt";
    //String payload = null;
     try {
        FileWriter fw = new FileWriter(fileName);
        BufferedWriter bw =new BufferedWriter(fw);  
        bw.write(in);                       
        System.out.println("Received "+in.length()+" bytes: ");  
        bw.close();
     }
     catch(IOException ex) {
        System.out.println("Error writing to file '"+ fileName + "'");
     }

    }


    public static String readFile()
    {
        String fileName = "temp.txt";
        String line = null;
        String Sentence = null;
        try {            
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        while((line = br.readLine()) != null) {
            //Sentence += line+'\n';
            Sentence = line +'\n';
        }
        br.close();
        System.out.println("Sending file "+fileName);
        return Sentence;
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileName + "'"); 
            return null;
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");   
            return null;
        // Or we could just do this: 
        // ex.printStackTrace();
        }
    }
    }

文字文件: 我大约三点钟从市里回来##% 五月下午对生活很反感。 我曾在旧国度过三个月,而且是 厌倦了它。

输出: read方法从文本文件中读取第一行并将该行写入输出文件...

我是编程新手,非常感谢帮助!

1 个答案:

答案 0 :(得分:0)

要创建输出文件,请尝试以下操作:

PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.println(in);
writer.close();

当您从文件中读取时,您应该通过执行

将行附加到原始变量
Sentence += line+'\n';