我想编一个读取一个文档的内容,并将其输出到另一个文档并加些内容(条件是在一个文件夹里有相同的文件夹才会将对应的信息输入到另个文档里),
import java.io.*;
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
File cheak = new File("C:/Users/Administrator/Desktop/Cheaklist.txt");
try
{
FileWriter fw = new FileWriter(cheak);
File fileName = new File("C:/Users/Administrator/Desktop/123.txt");
int i = 0 ;
while (i <= 45 )
{
Scanner In = new Scanner(fileName);
while(i <= 45)
{
String n = In.nextLine();
File file = new File("C:/Users/Administrator/Desktop/123/" + new String(n) );
if (file.exists())
{
String str = new String(n);
fw.write(str+" 1");
fw.write("\r\n"+str);
System.out.println(i);
}
else
{
}
fw.close();
i++;
}
i++;
In.close();
}
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
System.out.println("文件不存在或者文件不可读或者文件是目录");
}
}
}
我是个初学者,希望能用较通俗的语言讲解一下,或者发给我一个实例让我理解,或者帮我修改一下上面的错误,谢谢。
不知道个文件夹里有相同的文件夹是什么意思
FileWriter fw = new FileWriter(cheak);
你要注意,你写入的文件是这里的文件名,C:/Users/Administrator/Desktop/Cheaklist.txt,不是"C:/Users/Administrator/Desktop/123/" + new String(n)
而且,你在循环里直接调用fw.close();就给关闭了,之后的循环,显然就写不进去了,要么,你每次循环开始的时候都打开文件,要么,在循环后面再close
总之不知道你要做什么,但是以上不合理的地方,你可以参考下。
首先,看你的代码,是用户输入一个字符串后,当前目录下存在该文件,就写入到对应文件中。
其次 ,i< 45 为什么要有两层循环呢?为什么要以 45 为界限?
第三,内层循环接收输入的一个文件名称,读取文件后写入,没有问题。但是 scanner 不能关闭,修正下代码如下:
public static void main(String[] args) {
File cheak = new File("C:/Users/Administrator/Desktop/Cheaklist.txt");
FileWriter fw = null;
try
{
FileWriter fw = new FileWriter(cheak);
File fileName = new File("C:/Users/Administrator/Desktop/123.txt");
int i = 0 ;
Scanner In = new Scanner(fileName);
while(i <= 45)
{
String n = In.nextLine();
File file = new File("C:/Users/Administrator/Desktop/123/" + new String(n) );
if (file.exists())
{
String str = new String(n);
fw.write(str+" 1");
fw.write("\r\n"+str);
System.out.println(i);
}
i++;
}
In.close();
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
System.out.println("文件不存在或者文件不可读或者文件是目录");
}finally{
if(fw!=null){
fw.close();
}
}
}