读取文本文件的不同方法有以下几种:
import java.io.*;
public class ReadTextFileExample {
public static void main(String[] args) {
try {
File file = new File("path/to/file.txt");
FileInputStream fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐的腾讯云相关产品:对象存储 COS(https://cloud.tencent.com/product/cos)
import java.io.*;
public class ReadTextFileExample {
public static void main(String[] args) {
try {
File file = new File("path/to/file.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐的腾讯云相关产品:云服务器 CVM(https://cloud.tencent.com/product/cvm)
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class ReadTextFileExample {
public static void main(String[] args) {
try {
Path path = Paths.get("path/to/file.txt");
BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐的腾讯云相关产品:云数据库 MySQL(https://cloud.tencent.com/product/cdb)
以上是读取文本文件的几种常见方法,具体选择哪种方法取决于文件的大小和读取需求。
领取专属 10元无门槛券
手把手带您无忧上云