gpt4 book ai didi

java - 写入文件 Java 时程序卡住

转载 作者:行者123 更新时间:2023-11-29 06:30:31 30 4
gpt4 key购买 nike

因此,我的任务是从一个文件中读取文本并写入另一个文件,将所有文本更改为大写。我不确定为什么,但是当我运行它时,它会在我输入要写入的文件后卡住。非常感谢任何帮助。

import java.io.*;
import java.util.Scanner;

public class McKinneyBenjaminUpperFile
{
public static void main(String [] args)throws IOException
{
Scanner keyboard = new Scanner(System.in);

System.out.println("Benjamin's Uppercase File Converter\n");

String file1;
String file2;

System.out.println("Enter the name of the file to read from.");
file1 = keyboard.nextLine();

File file1open = new File(file1);

if(!file1open.exists())
{
System.out.println("The file you entered does not exists.");
System.exit(0);
}

Scanner infile = new Scanner(file1);

System.out.println("Enter the name of the file to write to: ");
file2 = keyboard.nextLine();

File file2open = new File(file2);

if(file2open.exists())
{
System.out.println("The file you entered already exists.");
System.exit(0);
}

PrintWriter outfile = new PrintWriter(file2);

while(infile.hasNext())
{
for(int i=0;i<file2open.length();i++)
{
String line = infile.nextLine().substring(0,1);
String newLine = line.toUpperCase();
outfile.println(newLine);
}
}

System.out.println("Conversion complete. " + file1 + " is now converted to all uppercase in " + file2);
}
}

最佳答案

but when I run it, it freezes after I enter the file to write to

在这个循环中:

for(int i = 0; i < file2open.length(); i++) { ... }

file2open.length() 将返回 0,因为您还没有创建目标文件。另见 File.length() :

Returns: The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist.

因此循环永远不会被执行。这导致 infile.nextLine() 永远不会被调用,因此您的外部 while 循环将永远循环,因为 hasNext() 将不断返回

请注意,File 只是文件元数据(如名称和属性)的表示。要写入文件,请使用流或编写器类,例如 FileOutputStream

关于java - 写入文件 Java 时程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619830/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com