jeudi 5 novembre 2015

Concantenate user input Strings to convert into a complete file path (Java)

I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:

    import java.util.Scanner;
public class FilePractice {
  public static void main(String[] args) {

    //create a new File object
    File myFile = new File("/home/christopher/Desktop/myFile");

        System.out.println("Would you like to create a new file? Y or N: ");
        Scanner input = new Scanner(;
        String choice = input.nextLine();
            //do nothing
    }catch(IOException e) {
        System.out.println("Error while creating file " + e);
    System.out.println("'myFile' " + myFile.getPath() + " created.");

I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.

Perhaps my syntax is wrong?

If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).

Here is the expanded attempt:

try {
       System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
            String fileName = input.nextLine();
            System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
            String userFilePath = input.nextLine();
            File userFile = new File(userFilePath, fileName);
            System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
            String userChoice = input.nextLine();

            if (userChoice.equalsIgnoreCase("Y")) {
                //print for debug 
            }catch(IOException e) {
                System.out.println("Error while attempting to create file " + e);
            System.out.println("File created successfully");

My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.

Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.

Aucun commentaire:

Enregistrer un commentaire