【问题标题】:write to file with lineseperator使用行分隔符写入文件
【发布时间】:2016-01-25 12:58:33
【问题描述】:

我想写入文件并使文本在 50 个字母后使用新行。我的代码使它在控制台中的 50 个字母后有一个新行,但在文件中没有?有什么问题?

import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class Journal {

public static void journalWriter(){
    try{
        Scanner Scan = new Scanner(System.in);

        System.out.println("Enter company");
        String company = Scan.nextLine();

        System.out.println("Enter contact, if there is more than 1 contact     use (.) between the names");
        String contact = Scan.nextLine();


        System.out.println("Write meeting contents");
        String journalContents = Scan.nextLine();

        StringBuilder sb = new StringBuilder(journalContents);

            int i = 0;
            while ((i = journalContents.indexOf(" ", i + 50)) != -1) {
                sb.replace(i, i + 1, "\n");
            }

            System.out.println(sb.toString());


        File dir = new File("C:\\Users\\Arman\\Desktop\\JavaProjekt\\Meetingjournals\\");
        dir.mkdir();    

        String dateOfMeeting = new SimpleDateFormat("YYYY.MM.dd").format(new Date());


        File meetingJournal = new   File("C:\\Users\\Arman\\Desktop\\JavaProjekt\\Meetingjournals\\" + company + ".txt");




        FileWriter writeToFile = new FileWriter("C:\\Users\\Arman\\Desktop\\JavaProjekt\\Meetingjournals\\" + company + ".txt",true);

        if (!meetingJournal.exists()){
            meetingJournal.createNewFile();
        }

        BufferedWriter buffWriter = new BufferedWriter(writeToFile);


        buffWriter.write(dateOfMeeting + ("\t") + ("\t") +("\t") + "Company: " + company + ("\t") + "Contact: " + contact );
        buffWriter.newLine();
        buffWriter.newLine();
        buffWriter.write(journalContents);
        buffWriter.newLine();
        buffWriter.newLine();

        buffWriter.close();

        System.out.println("Journal saved");
        System.out.println("Press enter for journalmenu");
        Scan.nextLine();



        JournalMain.main(null);
        Scan.close();

    }catch (IOException except){
        except.printStackTrace();
    }
}

}

【问题讨论】:

    标签: java file line-breaks


    【解决方案1】:

    您正在将未格式化的日志内容写入文件。格式化后尝试写日记内容。

    替换这一行:

    buffWriter.write(journalContents);
    

    作者:

    buffWriter.write(sb.toString());
    

    【讨论】:

    • 感谢您尝试帮助我,但没有这样做:-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2019-05-11
    相关资源
    最近更新 更多