[英]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.