如何获取桌面的文件路径并在filewriter上实现?

问题描述 投票:0回答:1

简而言之,我想做的是创建一个名为 unSorted.txt 的文件,然后在其中放入随机数,但我希望该文件保存在桌面中。每次我尝试在文件编写器中实现文件路径(请参阅代码以获取更多参考)时,我都会收到一条错误消息,提示找不到文件。

 try {
            String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
            String filePath = desktopPath + File.separator + "unSorted.txt";

            File myFile = new File(filePath);
            if (myFile.createNewFile()) {
                FileWriter myWriter = new FileWriter(filePath);
                Random rand = new Random();
                for (int i = 0; i < 500; i++) {
                    int random = rand.nextInt(1000) + 1; 
                    myWriter.write(random + System.lineSeparator()); 
                }
                myWriter.close();
             
            
        } catch (IOException e) {
            System.err.println("An error occurred. Please try again.");
            e.printStackTrace();
        }

正如您从代码中看到的,我已经实现了 File myFile = myFile 因为我从 filewriter 得到的错误是找不到文件,所以我决定先创建文件

java filewriter
1个回答
0
投票

您的代码示例中缺少一个括号,但此代码确实有效。

尝试{ String DesktopPath = System.getProperty("user.home") + File.separator + "桌面"; String filePath = DesktopPath + File.separator + "unSorted.txt";

        File myFile = new File(filePath);
        if (myFile.createNewFile()) {
            FileWriter myWriter = new FileWriter(filePath);
            Random rand = new Random();
            for (int i = 0; i < 500; i++) {
                int random = rand.nextInt(1000) + 1; 
                myWriter.write(random + System.lineSeparator()); 
            }
            myWriter.close();
        } //missing bracket    
        
    } catch (IOException e) {
        System.err.println("An error occurred. Please try again.");
        e.printStackTrace();
    } 

第一次运行它时,您将在指定的文件路径中创建一个新文件。第二次运行代码时,它将检测文件是否存在并退出 if 块。如果您在执行时遇到问题,请包含错误和堆栈跟踪。如果您对代码的功能不满意,请提出更多问题。

© www.soinside.com 2019 - 2024. All rights reserved.