簡體   English   中英

如何在Java中的不同行上多次寫入文本文檔?

[英]How do you write to a text document multiple times on different lines in Java?

所以,最近,我的父親讓我做了一個涉及收集用戶名,密碼等的項目,這樣他就可以設置一個位置來查找他的所有登錄信息。

我有一個程序,可以在每次運行程序時成功收集信息並編寫新的文本文件。 我的目標是使信息存儲在SAME文件中,但每組信息之間有一個空格。

這是我的代碼(我道歉,我只有14歲):

package com.src.java;

import java.io.IOException;
import java.io.PrintWriter;

import java.net.MalformedURLException;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class Info {

    public static void main(String args[]) throws MalformedURLException,
            IOException, InterruptedException {
        boolean run = true;
        while (run) {
            JTextField companyName = new JTextField();
            JTextField userName = new JTextField();
            JTextField password = new JTextField();
            JTextField accountNumber = new JTextField();
            JTextField phoneNumber = new JTextField();
            JTextField address = new JTextField();

            UIManager.put("OptionPane.cancelButtonText", "Exit");
            UIManager.put("OptionPane.okButtonText", "Create File");
            Object[] message = { "Company name: ", companyName, "Username:",
                    userName, "Password:", password, "Account number:",
                    accountNumber, "Phone number:", phoneNumber, "Address:",
                    address, };
            int option = JOptionPane.showConfirmDialog(null, message,
                    "Fill out your info...", JOptionPane.OK_CANCEL_OPTION);
            if (option == JOptionPane.OK_OPTION) {
                String cN = companyName.getText();
                String uN = userName.getText();
                String pw = password.getText();
                String aN = accountNumber.getText();
                String pN = phoneNumber.getText();
                String ad = address.getText();

                PrintWriter writer = new PrintWriter(cN + ".txt", "UTF-8");

                writer.println("Company name: " + cN);
                writer.println("User name: " + uN);
                writer.println("Password: " + pw);
                writer.println("Account number: " + aN);
                writer.println("Phone number: " + pN);
                writer.println("Address " + ad);
                writer.close();

                System.out.println("Wrote file: " + cN + ".txt");
                Thread.sleep(500);
            } else {
                System.exit(0);
            }
        }
    }
}

您寫入的文件名隨着輸入的公司名稱而變化。 硬編碼文件名。

另外,將追加模式設置為true ...

如果要寫入同一文件,可以在追加模式下打開,這樣

new PrintWriter(new FileOutputStream(new File(filename),true));

true將以追加模式打開文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM