以下是几种不同的实现方法将字符串写入文件中的 Java 代码:
1、使用 BufferedWriter 类
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;public class Main {public static void main(String[] args) {String content = "要写入文件的内容";String filePath = "文件路径";try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {writer.write(content);} catch (IOException e) {e.printStackTrace();}}
}
2、使用 PrintWriter 类
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;public class Main {public static void main(String[] args) {String content = "要写入文件的内容";String filePath = "文件路径";try (PrintWriter writer = new PrintWriter(new FileWriter(filePath))) {writer.println(content);} catch (IOException e) {e.printStackTrace();}}
}
3、使用 Files 类
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;public class Main {public static void main(String[] args) {String content = "要写入文件的内容";String filePath = "文件路径";try {Path file = Path.of(filePath);Files.write(file, content.getBytes(), StandardOpenOption.CREATE);} catch (IOException e) {e.printStackTrace();}}
}
如您在阅读中发现不足,欢迎留言!!!