我想用Java编写一个程序,检查src是否存在(如果不是抛出FileNoot)
并复制内容src.txt到des.txt
并在开幕和闭幕打印两个文件的大小(Java).txt读写器在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"));
其次忽略文件声明,我想问一下如何将下面的开关情况下适应(系统indepent行)
为了增加一个阅读后的换行符。
第三,我想问一下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());
}
}
}
}
让人惊讶的是,这个预言文件http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html 在没有异常处理中最后块为接近();方法 ,但我的编译器抱怨处理 – hitter