前言
  • 我们程序猿开发一般都是在windows上开发,因此一些文件的保存路径都是windows的目录路径,而程序的正式运行却是在Linux服务器上,因此这些目录路径有可能就不适用了,我也是在项目中遇到了这个问题,所以特意写了测试代码来搞清楚它们的目录路径区别,这篇博客也希望可以帮助其他程序猿搞清楚这个问题,避免踩坑,这也是我的第一篇博客,如有错误,敬请指教!!!

文件目录区别

  • windows中目录会分为多个磁盘,多个磁盘下会有多个文件夹或文件;
  • 而Linux中是以文件夹来区分
  • windows目录示例
    • D:\var\pic\localPic\2021\01\20\CPR7fa797ec84744fae974e3ed48685812e.jpg
  • Linux目录实示例
    • /var/pic/localPic/2021/01/20/CPR0246aa52bae84509a553e64dff870cc0.jpg

测试代码

  1. 从网络中获取请求的图片,并保存在指定目录下var/pic/localPic/
    i. 项目路径/home/java/xxx.jar
public class FileWrite {
    private static Logger logger = LoggerFactory.getLogger(FileWrite.class);
	//图片1保存路径
    private static String SAVE_PATH1 = "var/pic/localPic/";
    //图片1网络地址
    private static String imgUrl1 = "https://t7.baidu/it/u=3065092861,1536340632&fm=193&f=GIF";
    
	//图片2保存路径
    private static String SAVE_PATH2 = "/var/pic/localPic/";
    //图片2网络地址
    private static String imgUrl2 = "https://t7.baidu/it/u=3094572255,3845920741&fm=193&f=GIF";
	//创建okhttp实例
    public static OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(100, TimeUnit.SECONDS)
            .readTimeout(200, TimeUnit.SECONDS)
            .build();
           
	//保存文件
    public void saveFile() throws Exception {
        System.out.println("启动---------------");
        //从网络获取文件并保存
        try {
        	Date nowDate = new Date();
        	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        	String nowDate = simpleDateFormat.format(now);
        	//文件保存路径后添加当前日期目录 例:/var/pic/localPic/2021/01/24
            String savePath = SAVE_PATH1+nowDate;
            //保存的文件名称 实际使用可以调用生成uuid或雪花算法
            String imageUuid = "CPR7fa797ec84744fae974e3ed48685812e";
            saveNovelImg(imgUrl1,imageUuid,savePath);
            //保存文件时的日志
            //保存的路径:var/pic/localPic/
            //save img path getAbsolutePath------/home/java/var/pic/localPic/2021/01/20CPR7fa797ec84744fae974e3ed48685812e.jpg
            //save img path getCanonicalPath-------/home/java/var/pic/localPic/2021/01/20CPR7fa797ec84744fae974e3ed48685812e.jpg
            //save img path getParentFile-------var/pic/localPic/2021/01
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
        	Date nowDate = new Date();
        	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        	String nowDate = simpleDateFormat.format(now);
        	//文件保存路径后添加当前日期目录 例:var/pic/localPic/2021/01/24
            String savePath2 = SAVE_PATH2+nowDate;
            //保存的文件名称 实际使用可以调用生成uuid或雪花算法
            String imageUuid2 = "CPR0246aa52bae84509a553e64dff870cc0";

            saveNovelImg(imgUrl2,imageUuid2,savePath2);
            //保存文件时的日志
            //保存的路径:/var/pic/localPic/
            //绝对路径
            //save img path getAbsolutePath-------/var/pic/localPic/2021/01/20/CPR0246aa52bae84509a553e64dff870cc0.jpg
            //标准路径
            //save img path getCanonicalPath-------/var/pic/localPic/2021/01/20/CPR0246aa52bae84509a553e64dff870cc0.jpg
            //父路径
            //save img path getParentFile-------/var/pic/localPic/2021/01

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存小说图片
     * @param imageUrl 		图片网络地址
     * @param imageUuid		图片保存名称
     * @return String  		返回保存的文件路径
     */
    public JSONObject saveNovelImg(String imageUrl, String imageUuid,String imageSavePath) throws Exception{
        JSONObject result = new JSONObject();
        String imageName = "";
        Response response = getRequestResponse(imageUrl);
        //打开链接
        InputStream inStream = response.body().byteStream();
        byte[] data = readInputStream(inStream);
        //new一个文件对象用来保存图片,默认保存当前工程根目录
        String imagePath = imageSavePath;
        File ImageDir = new File(imagePath);
        if(!ImageDir.exists()){
            ImageDir.mkdirs();  //创建目录
        }
        imageName = imageUuid + ".jpg";

        //linux中
        System.out.println(imagePath);
        System.out.println(imagePath + imageName);
        System.out.println(imagePath+"/"+imageName);
        File imageFile = new File(imagePath +"/"+ imageName);
        File imageFile2 = new File(imagePath + imageName);
        logger.info("save img path getAbsolutePath-------"+imageFile.getAbsolutePath());
        logger.info("save img path getCanonicalPath-------"+imageFile.getCanonicalPath());
        logger.info("save img path getParentFile-------"+imageFile.getParentFile());
        logger.info("save img path getAbsolutePath-------"+imageFile2.getAbsolutePath());
        logger.info("save img path getCanonicalPath-------"+imageFile2.getCanonicalPath());
        logger.info("save img path getParentFile-------"+imageFile2.getParentFile());

        //创建输出流
        FileOutputStream outStream = new FileOutputStream(imageFile);
        //写入数据
        outStream.write(data);
        //关闭输出流
        outStream.close();
        String bookImageUrl = imageFile.getAbsolutePath();
        result.put("bookImageUrl",bookImageUrl);
        return result;
    }


	/**
     * 将图片流写入内存并返回
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

	/**
     * 获取请求的响应结果
     * @param requestUrl
     * @return 
     * @throws Exception
     */
    public Response getRequestResponse(String requestUrl) throws Exception{
        Request request = new Request.Builder()
                .url(requestUrl)
                .method("GET", null)
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }

结果
Linux
  • 项目路径:/home/java/xxx.jar
  • 保存路径1:/var/pic/localPic/
  • 保存路径2:var/pic/localPic/
  • 保存路径1结果:/home/java/var/pic/localPic/2021/01/24/CPR7fa797ec84744fae974e3ed48685812e.jpg
  • 保存路径2结果:/var/pic/localPic/2021/01/24/CPR0246aa52bae84509a553e64dff870cc0.jpg
  • 区别:目录前加‘/’会将图片保存至与项目同级的目录下,不加则保存至指定目录下
windows
  • 项目路径:D:\vv\project\springboot-web01
  • 保存路径1:/var/pic/localPic/
  • 保存路径2:var/pic/localPic/
  • 保存路径1结果:D:/vv/project/springboot-web01/var/pic/localPic/2021/01/24/CPR7fa797ec84744fae974e3ed48685812e.jpg
  • 保存路径2结果:D:/var/pic/localPic/2021/01/24/CPR0246aa52bae84509a553e64dff870cc0.jpg
  • 区别:目录前加‘/’会将图片保存至项目文件的目录下,不加则保存至项目同磁盘的指定目录下
结论
  1. 我们有时在windows中写文件路径会写D://vv//project//springboot-web01,建议不要这样写,否则将项目迁移至linux环境需要重写文件路径(除非要读取windows中与项目不同的磁盘下路径文件)
  2. 建议将文件路径写为:/var/pic/localPic/ 这种格式可以与Linux环境共用
  3. 注意路径前的 / :‘/’ 代表当前文件路径,无 ‘/’ 则指向根目录

更多推荐

java操作Linux与windows文件目录