gpt4 book ai didi

java - 文件(读写)无法正确检测到换行符

转载 作者:行者123 更新时间:2023-12-01 13:06:14 27 4
gpt4 key购买 nike

我想用Java编写一个程序来检查src是否存在(如果不抛出FileNoot的话)
并将src.txt的内容复制到des.txt
并在开头和结尾处打印两个文件的大小

输出为:

src.txt is in current directory
Before opening files:Size of src.txt:43 Bytes Size of des.txt:0 Bytes
After closing files:Size of src.txt:43 Bytes Size of des.txt:0 Bytes


src.txt将其内容写入des.txt后,des应该为43个字节
首先,我想问一下我是否可以通过写省略文件声明

PrintWriter outStream = new PrintWriter(new FileWriter("des.txt")); 


而且如果我需要同时 close()文件和流
其次,我想问一下如何适应以下切换情况(系统独立换行)
为了增加一个换行符,在读完之后。

第三,我想问一下关闭文件时try / catch块的重要性
对于这种类型的问题,我们感到非常抱歉,但是在C语言中,没有错误处理(我认为)close()肯定可以工作

对于这些类型的问题,我感到很抱歉,但是我是Java的初学者

import java.io.*;
public class Main
{
public static void main()throws FileNotFoundException
{

File src = new File("src.txt");
if(src.exists())
System.out.println("src.txt is in current directory");
else throw new FileNotFoundException("src.txt is not in current directory");

BufferedReader inStream = null;
PrintWriter outStream = null;
try{
File des = new File("des.txt");
inStream = new BufferedReader(new FileReader(src));
outStream = new PrintWriter(new FileWriter(des));

System.out.print("Before opening files:Size of src.txt:"+src.length()+" Bytes\t");
System.out.println("Size of des.txt:"+des.length()+" Bytes");
int c;
while((c = inStream.read()) != -1){
switch(c){
case ' ': outStream.write('@');
break;
case '\r':
case '\n':outStream.write('\n');
outStream.write('\n');
break;
default:outStream.write(c);
}
}
System.out.print("After closing files:Size of src.txt:"+src.length()+" Bytes\t");
System.out.println("Size of des.txt:"+des.length()+" Bytes");

} catch(IOException io) {
System.out.println("Read/Write Error:"+io.toString());
} finally {
try{
if (inStream != null) {
inStream.close();
}

if (outStream != null) {
outStream.close();
}
} catch (IOException io){
System.out.println("Error while closing Files:"+io.toString());
}
}
}
}

最佳答案

第一个问题->我想问一下我是否可以通过写省略文件声明

PrintWriter outStream =新的PrintWriter(新的FileWriter(“ des.txt”));

是的,您可以做到,因为文件编写器具有以下5种方式

FileWriter(File file)
Constructs a FileWriter object given a File object.
FileWriter(File file, boolean append)
Constructs a FileWriter object given a File object.
FileWriter(FileDescriptor fd)
Constructs a FileWriter object associated with a file descriptor.
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

关于java - 文件(读写)无法正确检测到换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23244308/

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