Copying files with java!? [SOLVED]

I want to copy my jar file from where ever to %appdata%!
here is my code:


	private void copy() throws IOException {
		InputStream is = getClass().getResourceAsStream("client.jar");
		OutputStream os = new FileOutputStream("%appdata%/client.jar");
		byte[] buffer = new byte[4096];
		int length;
		while ((length = is.read(buffer)) > 0) {
			System.out.println(buffer[length]);
			os.write(buffer, 0, length);
		}
		os.close();
		is.close();
	}

and get this error:


java.io.FileNotFoundException: %appdata%\client.jar (The system cannot find the path specified)
	at java.io.FileOutputStream.open(Native Method)
	at java.io.FileOutputStream.<init>(Unknown Source)
	at java.io.FileOutputStream.<init>(Unknown Source)
	at necro.green.client.Client.copy(Client.java:99)
	at necro.green.client.Client.main(Client.java:87)

I know my code is crap, so please help!

Edit:


Files.copy(Paths.get("client.jar"), Paths.get(System.getProperty("user.home") + "/AppData/Roaming/client.jar"));

This works thanks to : BurntPizza and Kefwar

Well… it’s not finding the file specified. I can guarantee you %appdata% is not a directory, but rather an environment variable storing the Roaming directory.

Java doesn’t know about Windows shell variables. Try this: http://stackoverflow.com/questions/9235734/how-to-get-the-value-of-windows-appdata-location-variable-in-java

Instead of specifying the path using %appdata%, you should instead try doing the following:

System.getProperty("user.home")

This will get you to C:/Users/GNecro1 in the case of Windows. From here, you can go into the AppData folder.

EDIT: Awww. I was ninja’d. :frowning:

my code now but still not working :-\ !


	private void copy() throws IOException, URISyntaxException {
		InputStream is = getClass().getResourceAsStream(getClass().getProtectionDomain().getCodeSource().getLocation().toURI().toString());
		OutputStream os = new FileOutputStream(System.getProperty("user.home")+ "/AppData/Roaming/client.jar");
		byte[] buffer = new byte[4096];// null pointer exception
		int length;
		while ((length = is.read(buffer)) > 0) {
			os.write(buffer, 0, length);
		}
		os.close();
		is.close();
	}

Error :


Exception in thread "main" java.lang.NullPointerException
	at necro.green.client.Client.copy(Client.java:99)
	at necro.green.client.Client.main(Client.java:88)

I’m guessing that’s the inputstream being null, indicating that path doesn’t exist/is incorrect.

Try using Java 7:

[icode]Files.copy(Paths.get(“input path here”), Paths.get(“output path here”));[/icode]

Probably way less flaky than using raw streams, also gives better error msgs IIRC.

Code :


		try {
			Files.copy(Paths.get("client.jar"), Paths.get(System.getProperty("user.home") + "/AppData/Roaming"));
		} catch (IOException e) {
			e.printStackTrace();
		}

Error:


java.nio.file.FileAlreadyExistsException: E:\Users\Necro\AppData\Roaming
        at sun.nio.fs.WindowsFileCopy.copy(Unknown Source)
        at sun.nio.fs.WindowsFileSystemProvider.copy(Unknown Source)
        at java.nio.file.Files.copy(Unknown Source)
        at necro.green.client.Client.main(Client.java:84)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)

Should I give up???

No: the folder Roaming exists,


Files.copy(Paths.get("client.jar"), Paths.get(System.getProperty("user.home") + "/AppData/Roaming"));

Change it to:


Files.copy(Paths.get("client.jar"), Paths.get(System.getProperty("user.home") + "/AppData/Roaming/client.jar"));

You are trying to overwrite the whole Roaming folder :wink:

Why didn’t anyone mention [icode]System.getenv(“APPDATA”);[/icode] yet? It returns the appdata folder’s filepath. :slight_smile:

It’s in the SO I linked…

[OT] If you are working on platforms other than windows, i recommend this code for the folder finding.

 /**
     * Returns a {@code File} that points to the application data with the
     * specified path. The directory returned will be a subdirectory with the
     * application's name, in the platform-specific location for storing
     * application data. If the subdirectory does not already exist it is
     * created.
     * 
     * @param appName
     *            The name of the application.
     * @param path
     *            Relative path to the requested file.
     * @return A {@code File} object that points to the requested file.
     * @throws IllegalArgumentException
     *             if the path is empty or absolute.
     */
    public static File getApplicationData(String appName, String path) {

        if (appName.length() == 0) {
            throw new IllegalArgumentException("Invalid application name");
        }

        if ((path.length() == 0) || path.startsWith("/")) {
            throw new IllegalArgumentException("Invalid path: " + path);
        }

        File appdir = null;

        if (System.getProperty("os.name").startsWith("Windows")) {
            appdir = new File(System.getenv("APPDATA"));
        } else if (System.getProperty("os.name").startsWith("Mac OS X")) {
            // This will also work for non-English versions of Mac OS X
            appdir = new File(System.getenv("HOME")
                    + "/Library/Application Support");
        }

        // If auto-detection failed, or if not known, fall back to user home
        if ((appdir == null) || !appdir.exists() || !appdir.isDirectory()) {
            appdir = new File(System.getProperty("user.home"));
            appName = "." + appName;
        }

        File dir = new File(appdir, appName);
        if (!dir.exists()) {
            boolean success = dir.mkdir();
            if (!success) {
                throw new IllegalStateException("Cannot create directory: "
                        + dir.getAbsolutePath());
            }
        }

        return new File(dir.getAbsolutePath() + "/" + path);
    }

It is not written by me but i forgot the autor. sry…

ClaasJG