我如何使用Java在txt中添加新行,并且没有空白

问题描述 投票:0回答:2

enter image description here

当我在此txt文件中编写文本时,新字符串和旧的现有字符串之间没有空格,或者多余的行使我的其他算法混乱。


    public String writeStudent(String file, String name)
        {

            String txt = "";
            //set through put method

            try(FileWriter fw = new FileWriter(file + ".txt", true);
                BufferedWriter bw = new BufferedWriter(fw);

                    PrintWriter out = new PrintWriter(bw))
            {

                out.println(name + "\r\n");


                //save userinput into class1.txt

                txt ="added: " + name;

             }

            catch(IOException e)
            {
                System.out.println("error");
                e.printStackTrace();
                // detact error
            }
    return txt;
    }

这是我用来写txt的代码,使用(name +“ \ r \ n”)给我多余的空行。

java file text-files filewriter bufferedwriter
2个回答
0
投票

如何使用BufferedWriter代替PrintWriter?

这是我的示例代码。请尝试测试以下代码。

import java.io.*;

public class Stackoverflow {
    public static void main(String[] args) {
        File file = new File("C:\\test.txt");
        OutputStream outputStream = null;
        Writer writer = null;
        BufferedWriter bufferedWriter = null;

        try {
            outputStream = new FileOutputStream(file);
            writer = new OutputStreamWriter(outputStream);
            bufferedWriter = new BufferedWriter(writer);

            bufferedWriter.write("Hello");
            bufferedWriter.write("\r\n");
            bufferedWriter.write("\r\n");
            bufferedWriter.write("Bye");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (Exception ignore) {

                }
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ignore) {

                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception ignore) {

                }
            }
        }

    }
}

输出

Hello

Bye

0
投票

问题是println函数自动在输入字符串的末尾添加新行。

out.println(name + "\r\n");实际上与out.print(name + "\r\n\r\n");]相同>

最后,您需要考虑换行是否需要在学生姓名之前或之后。

解决方案是简单地使用print而不是println并在学生姓名之前添加新行

例如。

给出现有的文本文件

John Doe

并且您希望将新名称添加为

John Doe
Jane Doe

换行符实际上是在您输入姓名之前。意味着您应该使用类似out.print("\r\n" + name);

的名称
© www.soinside.com 2019 - 2024. All rights reserved.