You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:PrintWriter无法写入Java文件的问题排查

Hey there! Let's fix this file handling issue you're having. I'll walk you through a complete, working solution and point out common pitfalls that might have tripped you up.

Step-by-Step Solution for Your File Task

First, here's a full, functional code implementation that does exactly what you need: creates a file with 10 random integers, then reads those values, multiplies each by 10, and writes the results to a second file.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class UghFiles {
    public static void main(String[] args) {
        // Define your file names (adjust paths if you need specific locations)
        String firstFile = "randomNumbers.txt";
        String secondFile = "scaledNumbers.txt";

        // Step 1: Write 10 random integers to the first file
        try (PrintWriter writer = new PrintWriter(new File(firstFile))) {
            Random random = new Random();
            for (int i = 0; i < 10; i++) {
                int randomNum = random.nextInt(100); // Generates 0-99, tweak range if needed
                writer.println(randomNum);
                System.out.println("Wrote: " + randomNum); // Optional: Verify what's being saved
            }
            // No manual flush() needed here—try-with-resources handles closing, which flushes automatically
        } catch (FileNotFoundException e) {
            System.err.println("Could not create/write to first file: " + e.getMessage());
            return;
        }

        // Step 2: Read from first file, multiply values by 10, write to second file
        try (Scanner reader = new Scanner(new File(firstFile));
             PrintWriter scaledWriter = new PrintWriter(new File(secondFile))) {

            while (reader.hasNextInt()) {
                int num = reader.nextInt();
                int scaledNum = num * 10;
                scaledWriter.println(scaledNum);
                System.out.println("Read " + num + ", wrote scaled value: " + scaledNum); // Optional verification
            }
        } catch (FileNotFoundException e) {
            System.err.println("File access error during reading/writing: " + e.getMessage());
        }

        System.out.println("Task completed! Check " + firstFile + " and " + secondFile);
    }
}

Key Fixes & Explanations

Let's break down the common issues that might have been causing your problem:

  • Try-With-Resources: This is the modern, safe way to handle file streams in Java. It automatically closes PrintWriter and Scanner objects when done, which guarantees all data is flushed to the file (no need for manual flush() unless you need it mid-operation). If you were manually opening/closing files, you might have forgotten to close them properly, leaving data stuck in buffers.
  • Proper File Reading: Your partial code didn't include the reading step—you need a Scanner (or another reader) to pull integers from the first file. Without this, you can't access the numbers to multiply them.
  • Error Handling: Added FileNotFoundException catches to alert you if files can't be created or accessed (e.g., permission issues, invalid file paths).
  • Clear File Paths: Using simple file names creates them in your project's root directory. If you need a specific location, replace the string with something like "C:\\Users\\YourName\\Documents\\randomNumbers.txt" (note double backslashes for Windows paths).

Quick Checks If It Still Doesn't Work

  • File Location: If using an IDE like Eclipse or IntelliJ, files are created in the project's root folder (not the src directory).
  • Permissions: Ensure your program has write access to the directory where you're creating files.
  • Random Number Range: The code uses nextInt(100) for 0-99—adjust this if you need larger numbers (e.g., nextInt(1000) for 0-999).

内容的提问来源于stack exchange,提问作者Everrick Wright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:40:21