1. 程式人生 > >java-createNewFile無法建立包含中文名路徑檔案

java-createNewFile無法建立包含中文名路徑檔案

package com.example.demo.util;

import com.example.demo.Controller.InfoController;

import java.io.BufferedWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.output.FileWriterWithEncoding;
import java.io.File;
import java.io.IOException;
/**
 * Created by bgy on 2018/1/24.
 */
public class FileUtil {
    public void builFile(String jsonfile){
        String rootPath = InfoController.class.getClassLoader().getResource("")
                .toString();
        rootPath = rootPath.replaceAll("%20", " ");
        rootPath = rootPath.replaceAll("file:/", "");
        Path path = Paths.get(rootPath).getParent().getParent();
        Path mypath = Paths.get(path.toString(), "src", "main", "resources","static","json");
        String realPath=mypath.toString();

        String filename = "maindata.json";
        String files = realPath + "\\" + filename;
        System.out.println(files);
        FileWriterWithEncoding fw = null;
        File f = new File(files);//files注意不包含中文路徑名
try { if (!f.exists()) { f.createNewFile(); } fw = new FileWriterWithEncoding(f, "UTF-8"); BufferedWriter out = new BufferedWriter(fw); out.write(jsonfile); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
檔案建立