为了账号安全,请及时绑定邮箱和手机立即绑定

我需要一个程序,它会要求用户输入要保存的信息,逐行保存在文件中。我该怎么做?

我需要一个程序,它会要求用户输入要保存的信息,逐行保存在文件中。我该怎么做?

慕少森 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 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信