Java 使用filereader从文件中读取文本
这是我的代码,用于从表中检索数据并将其写入文件,然后再次从文件中检索数据并将其显示在文本区域(ta)中。文件中的数据打印正常,但它仅显示文本区域中的最后一个字符,而不是显示整个数据。原因可能是什么?System.out.print没有刷新,错误已经提到:Java 使用filereader从文件中读取文本,java,sql,Java,Sql,这是我的代码,用于从表中检索数据并将其写入文件,然后再次从文件中检索数据并将其显示在文本区域(ta)中。文件中的数据打印正常,但它仅显示文本区域中的最后一个字符,而不是显示整个数据。原因可能是什么?System.out.print没有刷新,错误已经提到:ta.setText将使用当前字符重复覆盖ta,最后保留最后一个字符。此外,在正常的“…”字符串中,单个反斜杠会加倍一次 但我想提一下新课程。并尝试使用关闭文件、连接、语句和结果集的资源。也可以逐行读取。其中,readLine传递不带换行符的读取
ta.setText
将使用当前字符重复覆盖ta
,最后保留最后一个字符。此外,在正常的“…”字符串中,单个反斜杠会加倍一次
但我想提一下新课程。并尝试使用关闭文件、连接、语句和结果集的资源。也可以逐行读取。其中,readLine
传递不带换行符的读取行,或在文件末尾为null
我使用Unicode格式UTF-8来存储文件,以便能够组合任何脚本/特殊重音
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","jashan","noor1032");
PreparedStatement stmt=con.prepareStatement("select STUDENT_ID,STU_NAME,GENDER from STUDENT");
ResultSet rs=stmt.executeQuery();
FileWriter fw=new FileWriter("E:\\winter 2019\\COMP 230\\table.txt");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
fw.write(newline+rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
fw.close();
FileReader f1=new FileReader("E:\\\\winter 2019\\\\COMP 230\\\\table.txt");
BufferedReader br=new BufferedReader(f1);
int j;
String s;
while((j=br.read())!=-1)
{
char ch=(char)j;
s=new String (String.valueOf(ch));
System.out.print(s);
ta.setText(s);
}
f1.close();
您可能想考虑Apache CAMONS实用程序<代码> FILUTILLS类。它有一个方法
Path path = Paths.get("E:\\winter 2019\\COMP 230\\table.txt");
Class.forName("oracle.jdbc.driver.OracleDriver");
try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"...", "...");
PreparedStatement stmt = con.prepareStatement(
"select STUDENT_ID,STU_NAME,GENDER from STUDENT");
ResultSet rs = stmt.executeQuery();
PrintWriter pw = new PrintWriter(Files.newBufferedWriter(path))) {
pw.print('\uFEFF'); // Maybe write Unicode BOM for Windows Notepad
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
pw.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
try (BufferedReader br = Files.newBufferedReader(path)) {
String s;
while((s = br.readLine())!= null) {}
System.out.println(s);
ta.setText(ta.getText() + s + "\r\n");
}
}
这真的应该解决你所有的问题。查找此方法的javadoc。
你需要做的就是
public static String readFileToString(File file,
Charset encoding)
throws IOException
请尝试此代码。。。每次都会在textfield中重写值,而不是连接字符串然后将其写入textfield
ta.setText(FileUtils.readFileToString(new File("E:\\\\winter 2019\\\\COMP 230\\\\table.txt"), StandardCharsets.UTF_8));
在while循环中,将s的值更新为新值,并替换上一个,这就是为什么只看到最后一个字符。
String s;
StringBuilder text = new StringBuilder();
while((j=br.read())!=-1)
{
char ch=(char)j;
s=new String (String.valueOf(ch));
System.out.print(s);
text.append(s);
}
ta.setText(text.toString());
f1.close();