代码示例:
package filestring; import java.io.*; public class FileTest { public static void main(String[] args) { try { // 创建目录 File dir = new File("Chapter"); dir.mkdirs(); // 创建文件 File f = new File("D:/eclipseWJ/HelloWorld/Chapter/File1.txt"); f.createNewFile(); // 写入文件 FileWriter writer = new FileWriter(f); BufferedWriter bufferedwriter = new BufferedWriter(writer); bufferedwriter.write("File1"); bufferedwriter.close(); // 输出目录中的文件 if (dir.isDirectory()) { String[] fileContents = dir.list(); for (String i : fileContents) System.out.println(i); } // 读出文件内容 FileReader fileReader = new FileReader(f); BufferedReader reader = new BufferedReader(fileReader); String line = null; while ((line = reader.readLine()) != null) System.out.println(line); reader.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } }