I want to read a file from the user's desktop, and then write a new file to the desktop. Below is the code to do this on my own computer, but I'm not sure how to do it for any user.
I found this previously-asked question, but I'm not sure how to implement such a method in Java. Would I possibly use the System.getProperty()
method?
Any help or advice is appreciated. Thanks!
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)
{
}
}