【问题标题】:Java: reading file and then writting data on a text fileJava:读取文件然后将数据写入文本文件
【发布时间】:2015-07-19 20:57:30
【问题描述】:

如何在java中读取一个文件,然后将数据写入一个.txt文件?下面是我的代码。我正在阅读扩展名为 .ivt 的文件。 .ivt 中有一些表格,而 reset 是描述数据的全部内容的文本。我必须读取存储在文件中的文本,然后将其写入文本文件。我也能够获取数据并将其写入文本文件。但是,当我打开文本文件并查看写入的内容时,我看到许多行随机符号和空格。然后,几行从英语转换为法语。我正在努力寻找为什么会这样。读取数据时是否会出现此问题?还是代码有问题?

package description;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;

public class FileDescription
{
    public static void main(String[] args)
    {
        // create variables
        ArrayList<String> fileLines = new ArrayList<>();
        String currLine;

        // create file
        File file = new File("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\Products.ivt");

        FileInputStream fis = null;
        BufferedReader br = null;

        try
        {
            fis = new FileInputStream(file);
            // construct buffered reader
            br = new BufferedReader(new InputStreamReader(fis));
        }
        catch (FileNotFoundException e)
        {
        }

        try
        {
            while((currLine = br.readLine()) != null)
            {
                // add line to the arrayList
                fileLines.add(currLine);
            }
        }
        catch (IOException e)
        {
        }
        finally 
        {
            // close buffered reader
            try
            {
                br.close();
            }
            catch (IOException e)
            {
            }
        }

        // write ArrayList on file
        PrintWriter pw = null;

        try
        {
            pw = new PrintWriter("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt");
        }
        catch (IOException e)
        {
        }

        for (int i = 0; i < fileLines.size(); i++)
        {
            pw.println(fileLines.get(i));
        }
    }
}

【问题讨论】:

    标签: java file io readfile writefile


    【解决方案1】:

    代码似乎正确。只要记住也要关闭输出编写器。不指定任何其他内容,您使用的是平台编码。我认为这是一个编码问题。您可以尝试使用 UTF-8 编码进行读写。

    对于缓冲阅读器

    BufferedReader br = new BufferedReader(new InputStreamReader(
        new FileInputStream("filename.txt"), StandardCharsets.UTF_8));
    

    对于作者来说

    pstream = new PrintWriter(new OutputStreamWriter(
                        new FileOutputStream("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"), StandardCharsets.UTF_8), true);
    

    要编辑结果,请使用带有 UTF-8 的编辑器。

    Reference 1 Reference 2

    【讨论】:

    • 我也认为是编码问题。我知道您在读取文件时如何提到编码,但是,您能解释一下如何编写编码吗?我感到困惑的部分是 - csocket.getOutputStream()。另外,我将如何提供要写入的文件名?
    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2011-12-06
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    相关资源
    最近更新 更多