search

Home  >  Q&A  >  body text

java 文件路径问题

  1. 问题

windows下路径分割符'',java程序可识别的是'\'或'/',通过用户输入的路径进行转换,变成程序可识别的,但是转化后的路径程序不识别。

  1. 程序

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class test {

public static void main(String[] args) {
    // TODO 自动生成的方法存根
    String path=null;
    System.out.println("请输入文件路径");
    Scanner in=new Scanner(System.in);           //输入文件路径 "C:\Users\lenovo\Desktop\新建 Microsoft Excel 工作表.xlsx"
    path=in.nextLine().replaceAll("\\\\", "/");
    System.out.println(path);                    //得到系统识别的路径 path="C:/Users/lenovo/Desktop/新建 Microsoft Excel 工作表.xlsx"
    //path="C:/Users/lenovo/Desktop/新建 Microsoft Excel 工作表.xlsx";    
    File file=new File(path);                    //此时系统找不到文件,但是 将path="C:/Users/lenovo/Desktop/新建 Microsoft Excel 工作表.xlsx";执行后 程序能找到文件,问题就是 path已经是"C:/Users/lenovo/Desktop/新建 Microsoft Excel 工作表.xlsx",但程序不识别,怎么回事
    try {
        FileReader fileReader=new FileReader(file);
        System.out.println("读入文件");
    } catch (FileNotFoundException e) {
        // TODO 自动生成的 catch 块
        System.out.println("文件未找到");
    }
}

}

巴扎黑巴扎黑2804 days ago436

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:57:22

    -. - It seems that there is nothing wrong. Please compare the path you can successfully use (that is, the one you commented out) and the path converted after inputting it

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:57:22

    You can try

    "C:\Users\lenovo\Desktop\新建 Microsoft Excel 工作表.xlsx"

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:57:22

    I ran your code and it’s no problem. Chinese file names can also be recognized.

    reply
    0
  • Cancelreply