有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串从Java文件中读取windows文件名

背景

对于我正在编写的程序,我需要能够从文件中读取Windows文件名。不幸的是,Windows使用\而不是/,这使得这个问题变得棘手。我一直在尝试不同的方法,但似乎从未奏效。以下是Java代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test {
    static String localFile;
    static String localFilePrefix;
    static String user;

    public static void main(String[] args){
        readConfig("user.txt");
    }

    public static boolean readConfig(String cfgFilePath){
        try{
            BufferedReader reader = new BufferedReader(new FileReader(cfgFilePath));
            try{
                String line;
                while((line = reader.readLine()) != null){
                    if(line.indexOf("User") != -1){
                        user = line.substring(line.indexOf(" ")+1);
                    }else if(line.indexOf("LocalFile") != -1){
                        String tmp = line.substring(line.indexOf(" ")+1);
                        System.out.println("Test: " + tmp);
                        setLocalFile(tmp);
                    }
                }
            }catch(IOException ee){
                System.err.println(ee.getMessage());
            }
        }catch(FileNotFoundException e){
            System.err.println(e.getMessage());
        }
        return true;
    }

    public static void setLocalFile(String lFileName){
        System.out.println("FileName: " + lFileName);
        localFile = lFileName;
        if(new File(localFile).isDirectory()){
            System.out.println("Here!");
            localFilePrefix=localFile+File.separator;
        }
    }
}

下面是配置文件:

User test
LocalFile C:\User

使用该文件路径运行此代码不会打印Test: C:\Users,而应该打印。它也不打印FileName: C:\UsersHere!。但是,如果我从文件路径中删除“用户”,它会很好地工作,并打印出它应该打印的所有内容。它甚至将C:\识别为一个目录

问题

我不希望仅仅因为我的程序无法处理文件路径,就强迫用户以特殊格式写入文件路径。那么我该怎么解决这个问题呢


共 (1) 个答案

  1. # 1 楼答案

    第一个条件line.indexOf("User") != -1true用于输入User test,也用于LocalFile C:\User(对于包含User的每个路径都是如此)。因此,不评估else if条件

    ^{}代替^{}

    while ((line = reader.readLine()) != null) {
        if (line.startsWith("User")) {
            user = line.substring(line.indexOf(" ") + 1);
        } else if (line.startsWith("LocalFile")) {
            String tmp = line.substring(line.indexOf(" ") + 1);
            System.out.println("Test: " + tmp);
            setLocalFile(tmp);
        }
    }