Java中文本文件的读写IO操作及是否存在判断

JAVA判断文件或目录是否存在及创建并写入文本文件

//File对象的mkdirs()和mkdir()的区别
//mkdir:只能创建一级目录,例如”D:\a”,如果给的路径是多级目录,例如”D:\a\b\c”,则不会创建成功,不会有任何目录被创建,比较局限,个人不推荐使用。
//mkdirs:可以创建多级目录,例如” D:\a\b\c”,通常创建目录多使用此函数。
//等同WIN32API  CreateDirectory, ForceDirectories的区别和功能
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
	    String filePath = "D:\\Test";
	    File dir = new File(filePath);
	    // 一、检查放置文件的文件夹路径是否存在,不存在则创建
	    if (!dir.exists()) {
	        dir.mkdirs();// mkdirs创建多级目录
	    }
	    File checkFile = new File(filePath + "/filename.txt");
	    FileWriter writer = null;
	    try {
	        // 二、检查目标文件是否存在,不存在则创建
	        if (!checkFile.exists()) {
	            checkFile.createNewFile();// 创建目标文件
	        }
	        // 三、向目标文件中写入内容
	         // FileWriter(File file, boolean append),append为true时为追加模式,false或缺省则为覆盖模式
	        writer = new FileWriter(checkFile, true);
	        //在Windows操作系统中换行用fr.write("\n"); 是不行的,需要 fr.write("\r\n"); 即回车换行
	        writer.append("your content\r\n");
	        writer.flush();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (null != writer)
	            writer.close();
	    }
	}

JAVA根据路径读取文本文件到String字符串

//JAVA用于根据路径读取文件字符串
	public static String ReadFile(String Path){
        BufferedReader reader = null;
        String laststr = "";
        try{
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while((tempString = reader.readLine()) != null){
                laststr += tempString;
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }
发布了110 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/wh445306/article/details/103656637