上述代码调用close()方法关闭文件输入流对象fis。同样,你也需要关闭其他的输入输出流对象。 完整代码示例 下面是一个完整的示例代码,包括了以上提到的所有步骤: importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;publicclassFileExample{publicstaticvoidmain(String[]args){Filefile=newFile(...
new File(File parent,String child)//根据父目录文件+子路径构建 //new File(File parent,String child)//根据父目录文件+子路径构建 //在d盘下创建news2.txt File parentFile=new File("d:\\"); String fileName= "news2.txt"; File file=new File(parentFile,fileName); try { file.createNewFile()...
close方法通常是在try-with-resources语句中使用的,这样可以确保资源在使用完毕后会被自动关闭。例如: try (FileInputStream fis = new FileInputStream("file.txt")) { // 读取文件内容 } catch (IOException e) { e.printStackTrace(); } 复制代码 在上面的代码中,FileInputStream会在try语句块执行完毕后自...
file.close(); }catch(IOException e){} } } 或者用java7或更晚的版本中出现的try-with-resources: importjava.io.*;publicclassInputFile {publicstaticvoidmain(String [] args){inta = 0;try(FileInputStream file =newFileInputStream("G:\\java\\InputFile\\src\\InputFile.java")) {while((a = ...
publicclassReadFile{ publicstaticvoidmain(String[] args){ try{ FilemyObj=newFile("filename.txt"); ScannermyReader=newScanner(myObj); while(myReader.hasNextLine()) { Stringdata=myReader.nextLine(); System.out.println(data); } myReader.close(); ...
ObjectOutputStream objectOutputStream=newObjectOutputStream(newFileOutputStream("D:\\text.out"));Student student=newStudent();student.setAge(25);student.setName("jayWei");objectOutputStream.writeObject(student);objectOutputStream.flush();objectOutputStream.close(); ...
是的,你的new FileReader(file)是一个匿名对象。JVM中对于那些打开了没有关闭的IO文件流,会在不再被使用的情况下,等到下次做Full GC的时候把他们全部回收,尽量少使用这种写法。文章来自:http://blog.csdn.net/kongxx/article/details/6405914 public...
InputStream inputStream=newFileInputStream("D:\\log.txt");byte[]bytes=newbyte[inputStream.available()];inputStream.read(bytes);String str=newString(bytes,"utf-8");System.out.println(str);inputStream.close(); 1.3.2 OutputStream 使用 ...
导入java.io.File; 导入java.io.IOException; 公共类 CreateFileExample1 { 公共静态无效 主要(字符串 [] 参数) { 文件file =newFile("C:\\demo\\music.txt");//初始化文件对象并将路径作为参数传递布尔 结果; 尝试 { 结果= file.createNewFile();//创建一个新文件if(result)// 测试是否成功创建了一个...
CREATE_NEW- 创建新文件,如果文件已存在则失败 DELETE_ON_CLOSE- 当流关闭时删除文件 SPARSE- 提示文件系统创建稀疏文件 SYNC- 要求每次更新都同步写入存储 DSYNC- 要求每次更新都同步写入存储(仅内容) 示例2:指定打开选项 实例 importjava.io.IOException; ...