文件逆序输出
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("test1.in"));
BufferedWriter bw = new BufferedWriter(new FileWriter("test2.in"));
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
for (int i = list.size() - 1; i >= 0; i--) {
bw.write(list.get(i));
bw.newLine();
}
bw.close();
}
}
java.io.FileNotFoundException: filecopy.in (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at work7.FileCopyTest.main(FileCopyTest.java:9)
java.io.FileNotFoundException: filecopy.out (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at work7.FileCopyTest.main(FileCopyTest.java:36)
代码问题
【样例输入】设输入文件text1.dat为:
This is a test!
Hello, world!
How are you?
【样例输出】输出文件text2.dat为:
!tset a si sihT
!dlrow ,olleH
?uoy era woH
filecopy.in (系统找不到指定的文件。)
读写的文件位置不对,导致找不到。
test1.dat,text2.dat文件放在项目下,不要放在src下。
public static void main(String[] args) {
String txtPath = "D:/1111.txt"; //源文件路径
String outPath = "D:/2222.txt"; //目标文件路径
List<String> list = new ArrayList<>();
/* 读取数据 */
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(txtPath)),
"UTF-8"));
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
list.add(lineTxt);
}
br.close();
} catch (Exception e) {
System.err.println("read errors :" + e);
}
/* 输出数据 */
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPath)), "UTF-8"));
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
String[] split = s.split("");
String outs = "";
for (int j = split.length; j > 0; j--) {
outs += split[j-1];
}
bw.write(outs + "\r\n");
}
bw.close();
} catch (Exception e) {
System.err.println("write errors :" + e);
}
}
文件名不是 test1.dat吗,你这test1.in 是什么鬼
如果你是在工程中直接写了文件名是找不到的,因为File定义的基础路径是工程目录,但是当前java文件是有包名的,相当于:
读取的文件路径不对,找不到对应的文件,仔细检查一下文件名和路径