如何使用 java 在 txt 中添加新行并且没有空格

how can I add new lines in txt using java, and without empty spaces

当我在这个 txt 文件中写入文本时,新字符串和现有旧字符串之间没有 space,或者有额外的行,这打乱了我的其他算法。


    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") 给我额外的空行。

BufferedWriter 代替 PrintWriter 怎么样?

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

import java.io.*;

public class Whosebug {
    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

问题是 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);