【问题标题】:Why won't the BufferedWriter instantiation write to a txt file in Java?为什么 BufferedWriter 实例不会写入 Java 中的 txt 文件?
【发布时间】:2015-01-31 04:47:02
【问题描述】:

我正在尝试使用 BufferedWriter 实例化一个对象,但它不起作用。当我使用 write 功能时会出现问题。为什么它不让我写入文件? 错误是找不到符号。请帮我。我知道有人知道。这个是bufferedWriter方法为什么找不到符号?

package ex5_abcd;

import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;

public class EX5_ABCD {

    public static void main(String[] args) {
        boolean go = true;
        String firstN, lastN;
        String lineWritten = "";
        int IdNum;
        Scanner input = new Scanner(System.in);
        Path file = Paths.get("C:\\Java\\empList.txt");
        try {
            OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
            while (go) {
                System.out.println("Please enter Employee's First Name");
                firstN = input.nextLine();
                System.out.println("Please enter Employee's Last Name");
                lastN = input.nextLine();
                System.out.println("Please enter " + firstN + " " + lastN);
                IdNum = input.nextInt();
                lineWritten = IdNum + " " + firstN + " " + lastN;
                int lineLength = lineWritten.length();
                char [] testChar  =  new char[1];
            testChar [0] = 'a';
            writer = write(testChar, 0, lineLength); // Why write error
                writer.flush();
                writer.newLine();

            }
            writer.close();
        } catch (Exception e) {
            System.out.println("Error Msg:" + e);
        }
    }
}

【问题讨论】:

  • 取消注释刷新?
  • 仍然无法工作,兄弟,重复的 Sotirios Delimanolis 在哪里。先生,我想看看。
  • @SotiriosDelimanolis 我们可以取消欺骗吗,因为它不是真正的欺骗?
  • 还以为是重复的。
  • @JClassic 我建议你不要回答这样的问题。它们应该作为拼写错误或因为这个问题的解决方式不太可能帮助未来的读者而关闭。或作为具有给定规范答案的重复项关闭。我知道你现在没有声望,但当你有声望时,这就是你应该做的。

标签: java bufferedwriter writer


【解决方案1】:
writer = write(lineWritten, 0, lineLength);

应该改写成

writer.write(lineWritten, 0, lineLength); 

由于writer不是对对象的引用,所以应该调用writer对象的方法,不要将writer设置为其他值

回顾:

(=) 设置一个值。

此外,由于您从未在循环中将 go 的值设置为 false,因此您将继续在那里循环......永远......永远......我建议不要让这种情况发生

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2018-08-26
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多