首页 > 编程 > Java > 正文

java IO

2019-11-08 01:15:52
字体:
来源:转载
供稿:网友

总结出处:http://www.cnblogs.com/lich/archive/2011/12/10/2283445.html


File类的操作

//创建一个文件下的某个文件,先创建文件夹,否则会创建失败 //File 方法调用1.判断目录是否存在,2.创建目录,3.判断文件是否存在,4.删除文件 5.创建文件 //6列出目录下所有文件名称 6.得到目录下所有文件urlFile fdir = new File("C://Users//Administrator//Desktop"+File.separator+"basic");if(fdir.isDirectory()){ System.out.PRintln("is directory");}else{ System.out.println("is not directory,mkdir"); fdir.mkdir();}File ftxt1 = new File("C://Users//Administrator//Desktop"+File.separator+"basic"+File.separator+"ftxt1.txt");if(ftxt1.exists()){ System.out.println("ftxt1 is exists"); //ftxt1.delete();}else{ try { System.out.println("ftxt1 is not exists,creat"); ftxt1.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}String[] fStrs=fdir.list();for(int i=0;i<fStrs.length;i++){ System.out.println(fStrs[i]);}File[] files = fdir.listFiles();for(File f:files){ System.out.println(f);}

RandomaccessFile类

之前的File类只是针对文件本身进行操作的,而如果相对文件内容进行操作,则可以使用RandomAccessFile类,此类属于随即读取类,可以随机的读取一个文件中指定位置的数据。因为在文件中,所有得内容都是按照字节存放的,都有固定的保存位置。

public static void randomAccessFormText() throws IOException{ File file = new File("C://Users//Administrator//Desktop"+File.separator+"basic"+File.separator+"ftxt2.txt"); RandomAccessFile rf = new RandomAccessFile(file, "rw"); String name1 = "肖"; int age1 = 10; String name2="tto"; int age2 = 26; rf.writeUTF(name1); rf.writeInt(age1); rf.writeBytes(name2); rf.writeInt(age2); rf.close(); RandomAccessFile raf = new RandomAccessFile(file, "r"); raf.skipBytes(9); byte[] bs = new byte[3]; for(int i=0;i<bs.length;i++){ bs[i] = raf.readByte(); } String n2 = new String(bs); int ag2 = raf.readInt(); System.out.println(n2+"/t"+ag2); raf.seek(0); System.out.println(raf.readUTF()+"/t"+raf.readInt()); }

字节流字符流

public static void fileInputOutput() throws IOException{ //写入 字节流 File file = new File("C://Users//Administrator//Desktop"+File.separator+"basic"+File.separator+"ftxt2.txt"); OutputStream os = new FileOutputStream(file,true); String s = "Hello Word"; os.write(s.getBytes()); os.close(); //读取 字节流 InputStream is = new FileInputStream(file); byte[] bt = new byte[(int)file.length()]; is.read(bt); //System.out.println(new String(bt)); is.close(); //写入 字符流 Writer writer = new FileWriter(file,true); String s1 = "Jone"; writer.write(s1); //不关闭拼不上 writer.close(); //读出字符流 Reader reader = new FileReader(file); char[] c = new char[1024]; int len = 0; int temp = 0; while((temp=reader.read())!=-1){ c[len] = (char)temp; len++; } System.out.println(new String(c)); }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表