java怎么生成定长文件
时间: 2023-11-19 12:17:42 浏览: 50
在Java中生成定长文件,您可以使用Java的FileWriter类或RandomAccessFile类来实现。以下是两种方法的示例代码:
1. 使用 FileWriter 类
```java
import java.io.FileWriter;
import java.io.IOException;
public class FixedLengthFileWriter {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("fixed_length_file.txt");
String line1 = "123456789012345678901234567890"; // 30 characters
String line2 = "ABCDEFGHIJ1234567890"; // 20 characters
fw.write(line1);
fw.write(line2);
fw.close();
}
}
```
在上面的示例代码中,我们使用FileWriter类创建了一个名为“fixed_length_file.txt”的文件,并向其中写入了两行文本,分别为30个字符和20个字符。您可以根据您的需求更改这些文本行中的字符数。
2. 使用 RandomAccessFile 类
```java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FixedLengthRandomAccessFileWriter {
public static void main(String[] args) throws FileNotFoundException, IOException {
RandomAccessFile raf = new RandomAccessFile("fixed_length_file.txt", "rw");
String line1 = "123456789012345678901234567890"; // 30 characters
String line2 = "ABCDEFGHIJ1234567890"; // 20 characters
int lineLength = 50; // total characters in each line
raf.writeBytes(String.format("%-" + lineLength + "s%n", line1));
raf.writeBytes(String.format("%-" + lineLength + "s%n", line2));
raf.close();
}
}
```
在上面的示例代码中,我们使用RandomAccessFile类创建了一个名为“fixed_length_file.txt”的文件,并向其中写入了两行文本,分别为30个字符和20个字符。我们使用String.format()方法,以指定每行总长度为50个字符,并使用空格填充行中的空白位置。
以上是两种在Java中生成定长文件的方法。您可以根据您的需求选择其中一种方法来实现。