亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我需要一個程序,它會要求用戶輸入要保存的信息,逐行保存在文件中。我該怎么做?

我需要一個程序,它會要求用戶輸入要保存的信息,逐行保存在文件中。我該怎么做?

慕少森 2022-12-15 14:41:51
我需要一個程序,它會要求用戶輸入要保存的信息,逐行保存在文件中。我該怎么做?它必須看起來像這樣:Please, choose an option:1. Read a file2. Write in a new file2File name? problema.txtHow many lines do you want to write? 2Write line 1: HeyWrite line 2: How are you?Done! The file problema.txt has been created and updated with the content given. 我嘗試過各種方法,但沒有成功。首先,我在一個二維數組中完成了它,但我不能跳到下一行。然后我嘗試使用沒有數組的“.newline”方法,但它不能讓我保存一個以上的單詞。嘗試 1System.out.println("How many lines do you want to write? ");int mida = sc.nextInt();PrintStream escriptor = new PrintStream(f);String [][] dades = new String [mida][3];for (int i = 0; i < dades.length; i++) {  System.out.println("Write line " + i + " :");  for (int y=0; y < dades[i].length; y++) {    String paraula = sc.next();    System.out.println(paraula + " " + y);    dades[i][y] = paraula;    escriptor.print(" " + dades[i][y]);  }  escriptor.println();}嘗試 2System.out.println("How many lines do you want to write? ");int mida = sc.nextInt();PrintStream escriptor = new PrintStream(f);BufferedWriter ficheroSalida = new BufferedWriter(new FileWriter(new File(file1)));for (int i = 0; i < mida; i++) {  System.out.println("Write line " + i + " :");  String paraula = sc.next();  ficheroSalida.write (paraula);  ficheroSalida.newLine();  ficheroSalida.flush();}System.out.println("Done! The file " + fitxer + " has been created and updated with the content given. ");escriptor.close();嘗試 1:Write line 1: Hey How areWrite line 1: you...嘗試 2:Write line 1: HeyWrite line 2: HowWrite line 3: areWrite line 4: youWrite line 5: ?
查看完整描述

2 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

好吧,你快到了。首先,我會使用 ajava.io.FileWriter將字符串寫入文件。


如果您只是想將這些行寫入文件,那么實際上沒有必要在這里使用數組。


您還應該使用try-with-resources 語句來創建您的編寫器。這確保escriptor.close()即使出現錯誤也會被調用。在這種情況下您也不需要調用.flush(),因為這將在句柄關閉之前完成。你打算自己做這件事很好,但一般來說,盡可能使用這種特殊的聲明更安全。


import java.io.*;

import java.util.Scanner;


public class Example {


    public static void main(String[] args) {


        Scanner sc = new Scanner(System.in);

        File f = new File("/tmp/output.txt");


        System.out.println("How many lines do you want to write? ");

        int mida = sc.nextInt();

        sc.nextLine(); // Consume next empty line


        try (FileWriter escriptor = new FileWriter(f)) {


            for (int i = 0; i < mida; i++) {

                System.out.println(String.format("Write line %d:", i + 1));

                String paraula = sc.nextLine();

                escriptor.write(String.format("%s\n", paraula));

            }

        } catch (IOException e) {

            e.printStackTrace();

        }


    }


}


查看完整回答
反對 回復 2022-12-15
?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

如果您的文本文件很小并且不需要使用流閱讀器/流編寫器,您可以閱讀文本,添加您想要的內容并重新編寫。檢查這個例子:


public class ReadWrite {

    private static Scanner scanner;


    public static void main(String[] args) throws FileNotFoundException, IOException {

        scanner = new Scanner(System.in);

        File desktop = new File(System.getProperty("user.home"), "Desktop");

        System.out.println("Yo, which file would you like to edit from " + desktop.getAbsolutePath() + "?");

        String fileName = scanner.next();

        File textFile = new File(desktop, fileName);

        if (!textFile.exists()) {

            System.err.println("File " + textFile.getAbsolutePath() + " does not exist.");

            System.exit(0);

        }


        String fileContent = readFileContent(textFile);


        System.out.println("How many lines would you like to add?");


        int lineNumber = scanner.nextInt();


        for (int i = 1; i <= lineNumber; i++) {

            System.out.println("Write line number #" + i + ":");

            String line = scanner.next();

            fileContent += line;

            fileContent += System.lineSeparator();

        }


        //Write all the content again

        try (PrintWriter out = new PrintWriter(textFile)) {

            out.write(fileContent);

            out.flush();

        }

        scanner.close();

    }


    private static String readFileContent(File f) throws FileNotFoundException, IOException {

        try (BufferedReader br = new BufferedReader(new FileReader(f))) {

            StringBuilder sb = new StringBuilder();

            String line = br.readLine();


            while (line != null) {

                sb.append(line);

                sb.append(System.lineSeparator());

                line = br.readLine();

            }

            String everything = sb.toString();

            return everything;

        }

    }

}

該示例的執行將是:


Yo, which file would you like to edit from C:\Users\George\Desktop?

hello.txt

How many lines would you like to add?

4

Write line number #1:

Hello

Write line number #2:

Stack

Write line number #3:

Over

Write line number #4:

Flow

文件包含以下內容:


Hello

Stack

Over

Flow

如果您再次運行,輸入以下內容:


Yo, which file would you like to edit from C:\Users\George\Desktop?

hello.txt

How many lines would you like to add?

2

Write line number #1:

Hey

Write line number #2:

too

文本文件將包含:


Hello

Stack

Over

Flow

Hey

too

但是,如果您嘗試處理大文件,您的內存將不夠,因此OutOfMemoryError將拋出 an。但是對于小文件,沒問題。


查看完整回答
反對 回復 2022-12-15
  • 2 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號