复制一个已经存在的文本文件,生成一个新文件。 2、用PrintWriter流将九九乘法表写入到文件99.txt中。 3、将斐波那契数列的前10项写入到随机存取文件fei.dat中。 4、编程读取fei.dat文件中所有数据,计算其累加和,并添加到原有数据的后面。 5、将fei.dat文件的最后修改时间修改为前一天。
时间: 2024-02-15 08:04:13 浏览: 64
javaIO字符流文件写入总结共1页.pdf.zip
以下是Java代码实现所有要求:
1. 复制文件
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) throws IOException {
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
```
2. 写入九九乘法表
```java
import java.io.*;
public class WriteMultiplicationTableToFile {
public static void main(String[] args) throws IOException {
File file = new File("99.txt");
PrintWriter pw = new PrintWriter(file);
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
pw.print(j + "*" + i + "=" + (j * i) + "\t");
}
pw.println();
}
pw.close();
}
}
```
3. 写入斐波那契数列
```java
import java.io.*;
public class WriteFibonacciSequenceToFile {
public static void main(String[] args) throws IOException {
File file = new File("fei.dat");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
int[] fibonacci = new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
for (int i = 0; i < fibonacci.length; i++) {
raf.writeInt(fibonacci[i]);
}
raf.close();
}
}
```
4. 读取斐波那契数列并计算累加和
```java
import java.io.*;
public class ReadFibonacciSequenceFromFile {
public static void main(String[] args) throws IOException {
File file = new File("fei.dat");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
int sum = 0;
int length = (int) (raf.length() / 4);
for (int i = 0; i < length; i++) {
sum += raf.readInt();
}
raf.seek(raf.length());
raf.writeInt(sum);
raf.close();
}
}
```
5. 修改文件最后修改时间
```java
import java.io.*;
import java.util.Date;
public class ModifyFileLastModifiedTime {
public static void main(String[] args) {
File file = new File("fei.dat");
long lastModified = file.lastModified();
long oneDay = 24 * 60 * 60 * 1000L;
file.setLastModified(lastModified - oneDay);
}
}
```
阅读全文