1、读文件
相关文档:Java File文件处理 创建和写文件
Java中,读取文件通常有多种方式,可以使用FileReader
、BufferedReader
、Scanner
等。
1)使用 FileReader
读取文本文件
import java.io.FileReader; import java.io.IOException; public class FileReaderExample { public static void main(String[] args) { try (FileReader fr = new FileReader("example.txt")) { int character; while ((character = fr.read()) != -1) { System.out.print((char) character); // 打印每个字符 } } catch (IOException e) { e.printStackTrace(); } } }
2)使用 BufferedReader
读取文件(更高效)
BufferedReader
通过缓冲区来减少读取次数,适用于逐行读取文件。
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); // 打印每一行 } } catch (IOException e) { e.printStackTrace(); } } }
3)使用 Scanner
读取文件
Scanner
可以用于按行读取文件,也可以读取文件中的其他数据类型。
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { try (Scanner scanner = new Scanner(new File("example.txt"))) { while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); // 打印每一行 } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
4)使用 Files
类(Java 7+)
Java 7 引入了 java.nio.file.Files
类,可以轻松读取文件内容为 List<String>
。
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; import java.util.List; public class FilesExample { public static void main(String[] args) { try { List<String> lines = Files.readAllLines(Paths.get("example.txt")); for (String line : lines) { System.out.println(line); // 打印每一行 } } catch (IOException e) { e.printStackTrace(); } } }
2、获取文件信息
要获取有关文件的更多信息,需要使用任何File
方法:
例如:
import java.io.File; // Import the File class public class GetFileInfo { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); } else { System.out.println("The file does not exist."); } } }
注意:Java API中有许多可用的类,可用于读写Java中的文件:FileReader,BufferedReader,Files,Scanner,FileInputStream,FileWriter,BufferedWriter,FileOutputStream
等。具体使用取决于使用的Java版本以及是否需要读取字节或字符以及文件或行的大小等。
3、读取文件示例代码
常见的 Java 读取文件的示例代码,涵盖了不同的读取方式,包括按字节读取、按字符读取、按行读取等。
1)读取文件(以字节为单位)
import java.io.*; public class Main { public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; readFileByBytes(fileName); System.exit(0); //success } public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); System.out.println("当前字节输入流中的字节数为:" + in.available()); while ((byteread = in.read(tempbytes)) != -1) { System.out.write(tempbytes, 0, byteread); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { } } } } }
2)读取文件(以字符为单位)
import java.io.*; public class Main { public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; readFileByChars(fileName); System.exit(0); //success } public static void readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; try { System.out.println("以字符为单位读取文件内容,一次读一个字节:"); reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1) { if (((char) tempchar) != '\r') { System.out.print((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } try { System.out.println("以字符为单位读取文件内容,一次读多个字节:"); char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(new FileInputStream(fileName)); while ((charread = reader.read(tempchars)) != -1) { if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != '\r')) { System.out.print(tempchars); } else { for (int i = 0; i < charread; i++) { if (tempchars[i] != '\r') { System.out.print(tempchars[i]); } } } } } catch (Exception e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } }
3)读取文件(以行为单位)
import java.io.*; public class Main { public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; readFileByLines(fileName); System.exit(0); //success } public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } }
4)随机读取文件内容
import java.io.*; public class Main { public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; readFileByRandomAccess(fileName); System.exit(0); //success } public static void readFileByRandomAccess(String fileName) { RandomAccessFile randomFile = null; try { System.out.println("随机读取一段文件内容:"); randomFile = new RandomAccessFile(fileName, "r"); long fileLength = randomFile.length(); int beginIndex = (fileLength > 4) ? 4 : 0; randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; while ((byteread = randomFile.read(bytes)) != -1) { System.out.write(bytes, 0, byteread); } } catch (IOException e) { e.printStackTrace(); } finally { if (randomFile != null) { try { randomFile.close(); } catch (IOException e1) { } } } } }
4、将内容追加到文件尾部
要将内容追加到文件的尾部,可以使用 FileWriter
的 true
模式或 BufferedWriter
来实现。通过设置 append
参数为 true
,可以在文件末尾追加内容,而不是覆盖文件内容。
public class AppendToFile { /** * A方法追加文件:使用RandomAccessFile */ public static void appendMethodA(String fileName, String content) { try { // 打开一个随机访问文件流,按读写方式 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); //将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(content); randomFile.close(); } catch (IOException e) { e.printStackTrace(); } } /** * B方法追加文件:使用FileWriter */ public static void appendMethodB(String fileName, String content) { try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; String content = "new append!"; //按方法A追加文件 AppendToFile.appendMethodA(fileName, content); AppendToFile.appendMethodA(fileName, "append end. \n"); //显示文件内容 ReadFromFile.readFileByLines(fileName); //按方法B追加文件 AppendToFile.appendMethodB(fileName, content); AppendToFile.appendMethodB(fileName, "append end. \n"); //显示文件内容 ReadFromFile.readFileByLines(fileName); } }
相关文档: