import java.io.*; public class TestCopy1 { private static void createStuFile() throws IOException { File file = new File("fin.txt"); FileOutputStream fos = new FileOutputStream(file); String str = "Alcatel provides end-to-end solutions."; byte[] m = str.getBytes(); fos.write(m); fos.close(); } public static void main(String[] args) throws IOException { createStuFile(); File file = new File("fin.txt"); File file2 =new File("fout.txt"); FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file2); int x = fr.read(); while(x!=-1) { if((char)x==' '||(char)x=='\t') { x=(char)x; x.replaceAll(" +", " "); } System.out.print((char)x); fw.write(x); x = fr.read(); } fr.close(); fw.close(); } }代码改错
时间: 2024-01-01 20:03:47 浏览: 137
代码中有一个错误:在将字符替换为空格时,使用了 `replaceAll()` 方法,但该方法是 String 类的方法,不能直接应用于字符变量。应该改为使用字符常量 `' '` 来表示空格,并使用 `Character.toString()` 方法将其转换为字符串:
```
if ((char) x == ' ' || (char) x == '\t') {
x = ' ';
String space = Character.toString((char) x);
str = str.replaceAll(" +" + space, space);
}
```
另外,代码中的 `fw.write(x)` 应该是 `fw.write((char) x)`,否则写出的是字节而非字符。完整代码如下:
```java
import java.io.*;
public class TestCopy1 {
private static void createStuFile() throws IOException {
File file = new File("fin.txt");
FileOutputStream fos = new FileOutputStream(file);
String str = "Alcatel provides end-to-end solutions.";
byte[] m = str.getBytes();
fos.write(m);
fos.close();
}
public static void main(String[] args) throws IOException {
createStuFile();
File file = new File("fin.txt");
File file2 = new File("fout.txt");
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(file2);
int x = fr.read();
String str = "";
while (x != -1) {
if ((char) x == ' ' || (char) x == '\t') {
x = ' ';
String space = Character.toString((char) x);
str = str.replaceAll(" +" + space, space);
}
str += (char) x;
System.out.print((char) x);
fw.write((char) x);
x = fr.read();
}
System.out.println("\n\n" + str); // 打印替换后的字符串
fr.close();
fw.close();
}
}
```
阅读全文