Java 文件操作:字符串拼接、写入、读取和复制示例

本示例演示了使用 Java 进行文件操作的基本方法,包括将字符串拼接写入文件、读取文件内容和复制文件内容。代码使用字节流实现,并提供详细注释。

代码实现:

import java.io.*;

public class StringDemo {
    public static void main(String[] args) {
        try {
            // 循环随机输入三段字符串
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 1; i <= 3; i++) {
                System.out.println('请输入第' + i + '段字符串:');
                String str = reader.readLine();
                stringBuffer.append(str);
            }
            // 将拼接后的字符串写入文件
            FileOutputStream fileOutputStream = new FileOutputStream('c:\inputDemo.txt');
            fileOutputStream.write(stringBuffer.toString().getBytes());
            fileOutputStream.close();
            System.out.println('文件写入成功!');

            // 读取文件内容并打印
            FileInputStream fileInputStream = new FileInputStream('c:\inputDemo.txt');
            byte[] bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            String content = new String(bytes);
            System.out.println('文件内容为:' + content);
            fileInputStream.close();

            // 复制文件内容到另一个文件
            FileInputStream fileInputStream2 = new FileInputStream('c:\inputDemo.txt');
            FileOutputStream fileOutputStream2 = new FileOutputStream('c:\inputDemo2.txt');
            byte[] bytes2 = new byte[fileInputStream2.available()];
            fileInputStream2.read(bytes2);
            fileOutputStream2.write(bytes2);
            fileInputStream2.close();
            fileOutputStream2.close();
            System.out.println('文件复制成功!');

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

代码功能说明:

  1. 循环随机输入三段字符串: 使用 BufferedReader 从控制台读取用户输入的三段字符串,并使用 StringBuffer 将它们拼接起来。
  2. 将拼接后的字符串写入文件: 使用 FileOutputStream 创建文件输出流,并使用 write() 方法将拼接后的字符串写入文件 c:\inputDemo.txt
  3. 读取文件内容并打印: 使用 FileInputStream 创建文件输入流,使用 available() 方法获取文件大小,并使用 read() 方法将文件内容读入字节数组。最后将字节数组转换为字符串并打印出来。
  4. 复制文件内容到另一个文件: 使用 FileInputStreamFileOutputStream 分别创建两个文件流,将第一个文件的内容读入字节数组,并写入到第二个文件。

注意:

  • 代码中使用了 c:\inputDemo.txtc:\inputDemo2.txt 作为文件路径,请根据实际情况修改路径。
  • 代码中使用了字节流进行文件操作,如果需要处理文本文件,可以使用字符流。

希望本示例能够帮助您理解 Java 文件操作的基本原理。

Java 文件操作:字符串拼接、写入、读取和复制示例

原文地址: https://www.cveoy.top/t/topic/op6Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录