如何从 Java 中的文件中读取数据
How to read Data from File in Java
“使用 Java
代码从 File
读取数据,没有任何错误,也没有任何限制”。
使用files
的概念从文件中获取数据到程序中,下面给出代码。
这是从文件中读取数据的代码
import java.io.File;
import java.io.FileReader;
public class Demo17 {
public static void main(String[] args) throws Exception{
File f1 = new File("E:\usersData.txt"); //getting the file path
FileReader fr = new FileReader(f1); // reading the file data
char[] cArr = new char[(int) f1.length()]; // Creating an character array
fr.read(cArr); // Reading the character array
String s1 = new String(cArr); // converting to string array
System.out.println("Data present in File is : "+s1);
fr.close();
}
}
请查看官方 Java 文档中的 InputStream and Reader。
顺便说一句,如果您想读取原始数据,我建议您使用 FileInputStream, whereas, for text files, I would definitely check out FileReader.
这是一个示例代码:
File file = new File("file.txt");
try (FileReader fr = new FileReader(file))
{
int content;
while ((content = fr.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
或者您可以使用以下方法快速读取文件的所有行:
List<String> lines = Files.readAllLines(Path.of("file.txt"));
如果有帮助请告诉我:)
“使用 Java
代码从 File
读取数据,没有任何错误,也没有任何限制”。
使用files
的概念从文件中获取数据到程序中,下面给出代码。
这是从文件中读取数据的代码
import java.io.File;
import java.io.FileReader;
public class Demo17 {
public static void main(String[] args) throws Exception{
File f1 = new File("E:\usersData.txt"); //getting the file path
FileReader fr = new FileReader(f1); // reading the file data
char[] cArr = new char[(int) f1.length()]; // Creating an character array
fr.read(cArr); // Reading the character array
String s1 = new String(cArr); // converting to string array
System.out.println("Data present in File is : "+s1);
fr.close();
}
}
请查看官方 Java 文档中的 InputStream and Reader。 顺便说一句,如果您想读取原始数据,我建议您使用 FileInputStream, whereas, for text files, I would definitely check out FileReader.
这是一个示例代码:
File file = new File("file.txt");
try (FileReader fr = new FileReader(file))
{
int content;
while ((content = fr.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
或者您可以使用以下方法快速读取文件的所有行:
List<String> lines = Files.readAllLines(Path.of("file.txt"));
如果有帮助请告诉我:)