Java IO流如何操作(创建,读取,删除,写入)文件呢?
下文笔者将通过示例的方式讲述IO流操作文件的方法,如下所示:
创建一个新文件
import java.io.*; class TestClass{ public static void main(String[] args) { File f=new File("D:\\test.txt"); try{ f.createNewFile(); }catch (Exception e) { e.printStackTrace(); } } }
删除一个文件
import java.io.*; class TestClass{ public static void main(String[] args) { String fileName="D:"+File.separator+"test.txt"; File f=new File(fileName); if(f.exists()){ f.delete(); }else{ System.out.println("文件不存在"); } } }
IO流创建一个文件夹
import java.io.*; class TestClass{ public static void main(String[] args) { String fileName="D:"+File.separator+"test"; File f=new File(fileName); f.mkdir(); } }
列出指定目录的全部文件(包括隐藏文件)
import java.io.*; class TestClass{ public static void main(String[] args) { String fileName="D:"+File.separator; File f=new File(fileName); File[] str=f.listFiles(); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } }
使用RandomAccessFile写入文件
import java.io.*; class TestClass{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"test.txt"; File f=new File(fileName); RandomAccessFile demo=new RandomAccessFile(f,"rw"); demo.writeBytes("asdsad"); demo.writeInt(12); demo.writeBoolean(true); demo.writeChar('A'); demo.writeFloat(1.21f); demo.writeDouble(12.123); demo.close(); } }
向文件中写入字符串
import java.io.*; class TestClass{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"test.txt"; File f=new File(fileName); OutputStream out =new FileOutputStream(f); String str="java265.com"; byte[] b=str.getBytes(); out.write(b); out.close(); } }
向文件中追加新内容
import java.io.*; class TestClass{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"test.txt"; File f=new File(fileName); OutputStream out =new FileOutputStream(f,true); String str="Java265.com"; byte[] b=str.getBytes(); for (int i = 0; i < b.length; i++) { out.write(b[i]); } out.close(); } }
读取文件内容
import java.io.*; class TestClass{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"test.txt"; File f=new File(fileName); InputStream in=new FileInputStream(f); byte[] b=new byte[1024]; int count =0; int temp=0; while((temp=in.read())!=(-1)){ b[count++]=(byte)temp; } in.close(); System.out.println(new String(b)); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。