• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

第九章 IO操作

武飞扬头像
梁云亮
帮助1

9.1 目录操作

public class Dir1 {

	public static void main(String[] args) {
		//判断目录是否存在
		File f = new File("user");
		if(f.exists()) {
			System.out.println("user目录存在");
		}else {
			f.mkdir();//建立一级目录
			System.out.println("user目录建立成功");
			System.out.println(f.exists());
		}
		
		//建立目录 .mkdir()
		File f2 = new File("c:\\javaok\\book\\my\\user");
		if(!f2.exists()) f2.mkdirs(); //建立多级目录
		
		//建立多级目录  .mkdirs()
		File f3 = new File("c:/code/user");
		if(f3.mkdirs()) {
			System.out.println("建立成功");
		}else{
			System.out.println("已经存在不用建立");
		}
		
		
		//删除目录 只能删除一级空目录
		File f5 = new File("c:/code/abc");
		if(f5.exists() && f5.isDirectory()) {
			f5.delete(); //删除文件或删除一级空目录
		}
		
		File f6 = new File("c:/code");
		f6.delete();
	}

}

9.2 文件操作

  • java.io.File

    public class File1 {
    
    	public static void main(String[] args) throws IOException {
    		File f = new File("user");
    		System.out.println(f.isAbsolute());
    		System.out.println(f.isDirectory());
    		System.out.println(f.isHidden());
    		System.out.println(f.isFile());
    		System.out.println(f.exists());
    		
    		//建立文件
    		File uf1 = new File("user1.txt");
    		File uf2 = new File(".","user2.txt");
    		System.out.println(uf1.createNewFile());
    		System.out.println(uf2.createNewFile());
    		
    		//删除文件
    		if(uf1.exists()) uf1.delete();
    		if(uf2.exists()) uf2.deleteOnExit();
    
    	}
    
    }
    
    
    public class File2 {
    	public static void main(String[] args)  {
    		//File f = new File("c:/javaok/a.rar");
    		//f.deleteOnExit();
    		
    		File dir = new File("c:/javaok");
    		if(dir.exists()) {
    			File[] fs = dir.listFiles(); //列出当前目录下的所有文件对象
    			//System.out.println(fs.length);
    			for(File t : fs) {
    				if(t.isFile() && t.getName().endsWith(".rar")) {
    					t.delete();
    				}
    			}
    		}
    	}
    }
    
    
    统计文件代码行,空行数
    
    ```java
    public class File5 {
    	static int num = 0;
    
    	public static void main(String[] args) throws FileNotFoundException {
    		String path = "D:\\eclipse-workspace\\part02\\src\\cn\\Bin2.java";
    		BufferedReader br = new BufferedReader(new FileReader(path));
    		System.out.println(br.lines().filter(e->e.trim().length()>0).count());
    	}
    
    }
    
    

    递归统计文件个数及文件行数实现

    public class File4 {
    	static int num = 0;
        static int rows = 0;
        static int space = 0;
    	public static void main(String[] args) throws Exception {
    		String path = "c:/javaok";
    		
    		//del(new File(path));
    		
    		count(new File("d:/eclipse-workspace"));
    		
    		
    		System.out.printf("%s 共有%d个java程序文件%n","d:/eclipse-workspace",num); //java文件个数
    		System.out.printf("共 %d 行代码%n",rows);
    		System.out.printf("共 %d 空行代码%n",space);
    
    	}
    	
    	public static void count(File dir) throws FileNotFoundException  {
    		if (dir.isDirectory()) {
    			File[] f = dir.listFiles();
    			for (File t : f) {
    				if (t.isDirectory())
    					count(t);
    				if (t.isFile() && t.getName().endsWith(".java")) { 
    					  num;
    					BufferedReader br = new BufferedReader(new FileReader(t));
    					//rows =br.lines().filter(e->e.trim().length()>0).count();
    					rows =br.lines().count();
    					
    					BufferedReader br2 = new BufferedReader(new FileReader(t));
    					space =br2.lines().filter(e->e.trim().length()==0).count();
    				}
    					
    			}
    		} 
    		if (dir.isFile() && dir.getName().endsWith(".rar")) {
    			  num;
    			BufferedReader br = new BufferedReader(new FileReader(dir));
    			//rows =br.lines().filter(e->e.trim().length()>0).count();
    			rows =br.lines().count();
    			
    			BufferedReader br2 = new BufferedReader(new FileReader(dir));
    			space =br2.lines().filter(e->e.trim().length()==0).count();
    		}
    	}
    
    	public static void del(File dir) {
    		if (dir.isDirectory()) {
    			File[] f = dir.listFiles();
    			for (File t : f) {
    				if (t.isDirectory())
    					del(t);
    				if (t.isFile() && t.getName().endsWith(".rar"))
    					t.delete();
    			}
    		} 
    		if (dir.isFile() && dir.getName().endsWith(".rar"))
    			dir.delete();
    	}
    
    }
    
    

9.3 字节流

学新通

  • java.io.InputStream 输入流,主要是用来读取文件内容的。

  • java.io.OutputStream 输出流,主要是用来将内容写入文件的。

  • FileInputStream、 FileOutputStream

    public class FileStreamTest {
    	
    	public static void main(String[] args) {
    		//读取文件
    		String f = "D:\\java\\log\\20201222-type.txt";
    		try {
    			FileInputStream fis = new FileInputStream(f);
    			//System.out.println(new String(fis.readAllBytes(),"utf-8"));
    			
    			byte[] buf = new byte[1024];
    			int len = 0;
    			while((len = fis.read(buf))>0) {
    				System.out.println(new String(buf,"utf-8"));
    			}
    		
    			
    			fis.close();
    		}catch(Exception e) {
    			
    		}
    		
    	}
    	
    	
    	public static void write(String str) {
    		try {
    			//建立文件输出流,用来写入内容,true,追加模式
    			FileOutputStream fos = new FileOutputStream("c:/u.txt",true);
    			fos.write(String.format("hello world 中文效果(%1$tF %1$tT)\r\n", System.currentTimeMillis()).getBytes());
    			fos.close();
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    
  • 实现文件复制功能

    
    public class FileCopy {
    
    	public static void main(String[] args) throws IOException {
    		//实现文件复制
    		FileInputStream fis = new FileInputStream("c:/u.jpg");
    		//DataInputStream dis = new DataInputStream(fis);
    		FileOutputStream fos = new FileOutputStream("d:/u2.jpg");
    		//fos.write(fis.readAllBytes());
    		byte[] buf = new byte[1024];
    		int len = 0;
    		while((len = fis.read(buf))!=-1) {
    			fos.write(buf, 0, len);
    		}
    		fo
                s.close();
    		
    
    	}
    
    }
    
    
  • RandomAccessFile

    public class StreamTest {
    
    	public static void main(String[] args) throws IOException {
    		RandomAccessFile randf = new RandomAccessFile("c:/u.jpg", "r");
    		
    		//System.out.println(randf.length());
    		//System.out.println(randf.readByte());//-1
    		//System.out.println(randf.readByte());//-40
    		//System.out.println(randf.readByte());//-1
    		//randf.skipBytes(0);//0 -32 1 0   2 16
    		//System.out.println(randf.readByte());//16
    		
    		randf.skipBytes((int)randf.length()-1);
    		System.out.println(randf.readByte());
    
    	}
    
    }
    
    
  • ObjectInputStream\ObjectOutputStream

    public class User implements Serializable {
    	private int id;
    	private String name;
    	private int age;
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    
    	public User(int id, String name, int age) {
    		super();
    		this.id = id;
    		this.name = name;
    		this.age = age;
    	}
    
    	public User() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	@Override
    	public String toString() {
    		return "User [id="   id   ", name="   name   ", age="   age   "]";
    	}
    
    }
    
    public class ObjectStreamTest {
    
    	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    		// 将java为的实例保存
    		//User u = new User(1, "杰克", 18);
    		 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat", true));
    		 
    		 oos.writeObject("aa");
    		 
    
    
    		 List<User> us = new ArrayList<User>();
    		 oos.writeObject(us);
    
    		 
    		// oos.writeObject(u);
    		// oos.close();
    		
    		
    
    		// 读取Object
    		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"));
    		User user = (User)ois.readObject();
    		System.out.println(user);
    
    	}
    
    }
    
    
    

    面试题:java中什么是序列化,反序列化?为什么要序列化?

9.4 字符流

学新通

  • Reader FileReader BufferedReader

  • Writer FileWriter BufferedWriter

    
    public class ReaderWriterTest {
    
    	public static void main(String[] args) throws IOException {
    		//写入文件
    		FileWriter fw = new FileWriter("user.dat", true);
    		//fw.write("hello world中文\n\r");
    		//fw.write("hello world中文\n\r");
    		//fw.write("hello world中文\n\r");
    		//fw.close();
    		
    		//读取
    		BufferedReader br = new BufferedReader(new FileReader("user.dat"));
    		//System.out.println(br.lines().count());
    		int rownum = 0;
    		
    		while(br.ready()) {
    			  rownum;
    			System.out.println(br.readLine());
    		}
    		System.out.println(rownum);
    		br.close();
    	}
    }
    
    

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhhfha
系列文章
更多 icon
同类精品
更多 icon
继续加载