• java本地文件操作


    文件的创建删除重命名

    通过文件类的creatNewFile()方法创建文件,通过delete()方法删除文件,使用renameTo()方法重命名文件。

    文件夹的创建删除重命名

    通过使用mkdir()如果创建多级路径,要求路径存在。mkdirs()方法创建文件夹,可创建多级路径的文件夹,使用delete()方法删除文件夹,删除文件夹时必须要删除的文件夹为空,使用renameTo()方法重命名文件夹

    文件属性的读取

    返回文件名,为程序创建文件时的文件名

    文件夹属性的设置

    文件是否存在、文件名称、路径、文件大小、是否被隐藏、是否可读可写、是否为文件夹

    回父级路径为上级路径的名称。如果创建的时候是相对路径此时返回为空,可创建一个带绝对路径的文件,然后.GetParen

    SetWritable 参数设置为true设置为可写

    设置为false设置为不可写

    遍历文件夹

    使用listFiles()方法获取文件夹中的所有项目,并且通过递归显示完整的层级结构

    文件的简单读写

    不要忘记close

    public static void main(String[] args) {
    		File file = new File("text.txt");
    		try {
    			FileInputStream fis = new FileInputStream(file);
    			InputStreamReader isr = new InputStreamReader(fis);
    			BufferedReader br = new BufferedReader(isr);
    			String line;
    			try {
    				while ((line = br.readLine()) != null) {
    					System.out.println(line);
    				}
    
    				System.out.println("打印完毕");
    				br.close();
    				isr.close();
    				fis.close();
    			} catch (IOException e) {
    
    				e.printStackTrace();
    			}
    		} catch (FileNotFoundException e) {
    
    			e.printStackTrace();
    		}
    		File newfile = new File("newfile.txt");
    		try {
    			FileOutputStream fos = new FileOutputStream(newfile);
    			OutputStreamWriter osw = new OutputStreamWriter(fos);
    			BufferedWriter bw = new BufferedWriter(osw);
    			try {
    				bw.write("许多年前你有一双清澈的双眼
    ");
    				bw.write("奔跑起来像一道闪电
    ");
    				bw.write("相信自己
    ");
    				bw.write("一切都只是新的开始
    ");
    			
    				bw.write("抓住白天的时间,规律作息
    ");
    				System.out.println("done");
    				bw.close();
    				osw.close();
    				fos.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    

      

  • 相关阅读:
    POJ 3070 Fibonacci【矩阵连乘】
    hdu 3038 How Many Answers Are Wrong【并查集的简单应用】
    POJ 2236 Wireless Network 【并查集的简单应用 判断是否在同一连通分量】
    POJ 1984 Navigation Nightmare【并查集思路总结】
    POJ 2492 A Bug's Life【并查集的简单应用同类的判断】
    POJ 1703 Find them, Catch them【典型并查集:判断在不同的集合】
    POJ 1456 Supermarket【贪心 + 并查集】
    ZOJ 3261 Connections in Galaxy War【并查集】
    POJ 1984 Navigation Nightmare
    POJ 1988 Cube Stacking【并查集的简单应用 堆木块】
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4606808.html
Copyright © 2020-2023  润新知