Change a String (Put brackets around file name and get TWO Backslashes)

眉间皱痕 提交于 2019-12-24 19:48:11

问题


My project is based on Apache POI.I'm trying to use a formula on a cell. My formula is as follows.

sheet7.createRow(0).createCell(0).setCellFormula("+'C:\\Users\\Desktop\\[Test.xlsx]Average_Graph'!A2");

Im using a JFileChooser, which allows users to select the file. Therefore the filepath will be changed every time the program is used.

From the JFileChooser, I'm getting a filepath as follows.

String filepath= "C:\Users\Desktop\Sheet.xlsx

In order to work the formula correctly, the filepath should be in following format.

"C:\\Users\\Desktop\\[Sheet.xlsx]"

How Can I Change the string which I'm getting from the JFileCHooser to run the formula correctly? I need TWO backslashes instead of one. Please help.


回答1:


Try doing two replacements, one to handle the filename, the other to handle the formatting of the path:

String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.replaceAll("(?<=\\\\)([^\\\\]+)$", "[$1]").replace("\\, "\\\\");
System.out.println(filepath);

C:\\Users\\Desktop\\[Sheet.xlsx]



回答2:


I have written some function. Just pass the file absolute path and you will get the your output. May it helps....

public static String pathFormat(String path) {
        System.out.println("pathFormat1...");
        String formatStr="\"";
        StringTokenizer st=new StringTokenizer(path,"\\");
        while(st.hasMoreTokens()) {
            String nextToken = st.nextToken();
            System.out.println(nextToken);
            //formatStr+=nextToken;
            if(st.hasMoreTokens()) {
                formatStr+=nextToken;
                formatStr+="\\\\";
            }
            else {
                formatStr+="[";
                formatStr+=nextToken;
                formatStr+="]\"";
            }
        }


来源:https://stackoverflow.com/questions/52050242/change-a-string-put-brackets-around-file-name-and-get-two-backslashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!