簡體   English   中英

Java如何在任何用戶的桌面上讀寫文件

[英]Java How to read/write files to/from any user's desktop

我想從用戶的桌面讀取文件,然后將新文件寫入桌面。 下面是在我自己的計算機上執行此操作的代碼,但是我不確定如何為任何用戶執行此操作。

我發現了這個先前提出的問題,但是我不確定如何在Java中實現這種方法。 我可能會使用System.getProperty()方法嗎?

任何幫助或建議,不勝感激。 謝謝!

public static String [] read()
{
    ArrayList<String> fileArrList = new ArrayList<>();
    Scanner scan = new Scanner(System.in);
    System.out.print("File name > ");
    String fileName = scan.nextLine();

    try
    {
        Scanner file = new Scanner(new File("C:\\Users\\pez\\Desktop\\" + fileName));

        while (file.hasNextLine())
        {
            String line = file.nextLine();
            fileArrList.add(line);
        }

        file.close();

        String [] fileArr = new String[fileArrList.size()];
        fileArr = fileArrList.toArray(fileArr);

        return fileArr;
    }
    catch (FileNotFoundException fnfe)
    {
        System.out.println("File not found");
    }

    return null;
}

public static void writeNewFile(ArrayList outputArr)
{
    try
    {
        FileOutputStream fos = new FileOutputStream("C:\\Users\\pez\\Desktop\\output.txt", false);
        PrintWriter pw = new PrintWriter(fos);

        for (Object i : outputArr)
        {
            pw.println(i);
        }

        pw.close();
    }
    catch (FileNotFoundException fnfe)
    {
    }    
}  

您可以使用系統屬性user.home

    File desktop = new File(System.getProperty("user.home"), "/Desktop"); 
    Scanner file = new Scanner(new File(desktop, fileName));

我假設您知道您僅限於Windows環境。

我將給您提供一些簡單的示例,您可以在您的項目中實現這些示例。 要獲取Windows用戶名,您可以獲取屬性user.name

System.getProperty("user.name");

要寫文件,您可以使用以下簡單代碼:

PrintWriter writer = new PrintWriter("filename.txt", "UTF-8");
writer.println("Some text");
writer.println("Some other text");
writer.close();

要讀取文本文件,可以使用以下命令:

BufferedReader br = new BufferedReader(new FileReader("/path/to/filename.txt"));
String textLine = null;
while ((textLine = br.readLine()) != null) {
    System.out.println(textLine);
}

您可以在項目中輕松實現所有這些代碼。 希望對您有用,對不起我的英語。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM