【问题标题】:How to access file that have space character in it's name in using java? [closed]java - 如何在使用java时访问名称中包含空格字符的文件? [关闭]
【发布时间】:2020-04-09 20:15:06
【问题描述】:

我无法访问名称中包含空格的文件。

我的代码:

String fileName = "This is my file.txt";
String path = "/home/myUsername/folder/";
String filePath = path + filename;
f = new BufferedInputStream(new FileInputStream(filePath));

我收到FileNotFoundException

【问题讨论】:

标签: java linux file exception filenotfoundexception


【解决方案1】:

首先是参数文件名有错别字:

String **fileName** = "This is my file.txt";
    String filePath = path + **filename**;

这是您的示例的更新代码:

  String fileName = "This is my file.txt";
            String path = File.separator + "home" + File.separator + "myUsername" + File.separator + "folder" + File.separator;
            String filePath = path + fileName;
            BufferedInputStream f = new BufferedInputStream(new FileInputStream(filePath));

我可以读取文件名中带有空格的文件。

使用 File.separator 我们让代码替换基于文件的分隔符 在操作系统上。

【讨论】:

    【解决方案2】:
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    public class AccessMyFile {
        public static void main(String[] args) throws IOException {
            File file = new File("/home/This is my file.txt");
            System.out.println(file.exists());//true
            System.out.println(file.isFile());//true
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            while(bis.available()>0) {
                System.out.print((char)bis.read());
            }
        }//main
    }//class
    

    文件:/home/这是我的文件.txt

    输出:

    hello world
    

    使用 java.io.File 来检查是否存在。然后您就知道您的代码是否正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 2011-04-18
      • 2020-08-20
      • 2014-10-20
      • 2018-05-09
      相关资源
      最近更新 更多