java 文件读写代码如何读取文件?使用 files.readallbytes() 读取文件字节。将字节数组转换为字符串以获取文件内容。如何写入文件?使用 files.write() 将要写入的文件内容转换为字节数组。将字节数组写入指定文件路径。
Java 文件读写代码
如何读取文件?
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadFile {
public static void main(String[] args) {
try {
// 读取文件内容
String content = new String(Files.readAllBytes(Paths.get("test.txt")));
// 输出文件内容
System.out.println("文件内容:");
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}登录后复制
如何写入文件?
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteFile {
public static void main(String[] args) {
try {
// 写入文件内容
String content = "Hello world!";
Files.write(Paths.get("test.txt"), content.getBytes());
// 输出写入成功信息
System.out.println("写入文件成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}登录后复制以上就是java读写文件代码的详细内容,更多请关注php中文网其它相关文章!
RichardGlymn3 天前
发表在:Java webservice多个参数怎么调用https://t.me/win_1_c...
Thomasstolo5 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Casin...
Thomasstolo5 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
Thomasstolo6 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
Thomasstolo6 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Offic...
Charlesbeise8 天前
发表在:10日02日,星期四,在这里每天60秒读懂世界!Get free Blockchain ...
WalterSnula21 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Reyti...
WalterSnula22 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Reyti...
WalterSnula22 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Reyti...
WalterSnula22 天前
发表在:Java webservice多个参数怎么调用https://t.me/s/Reyti...