• snoofle (unregistered) in reply to Ant
    Ant:
    Hey now, you've got to give the guy _some_ credit: this would execute faster than Vista's built in copy routine.
    I haven't head the pleasure that is Vista yet - is it really that bad?!
  • Anon (unregistered) in reply to ailivac
    ailivac:
    The true WTF is that Java doesn't have a standard or sane way of installing extra libraries, so programmers have to reinvent broken wheels like this all the time.
    It does have a standard way - it just isn't sane. Assuming %JRE_HOME% is the JRE directory, you "simply" copy the JAR library into %JRE_HOME%\lib\ext.

    Things get really fun when you install the JDK, since it happily installs two copies of the JRE: on embedded next to the compiler and utilities, and one "normal" JRE. Why the two copies? It's Java. It doesn't have to make sense.

  • (cs) in reply to ailivac
    ailivac:
    I can't believe no one else has mentioned another huge error in this. I guess you people haven't worked with a unix shell enough to know which characters are OK to use in command lines and which need special processing.

    This is obviously designed to run on windows, where directories commonly have names like "My Documents," "Program Files" and "Application Data." All of those have a character in them that will make the batch file call fail instantly.

    I'm pretty sure the "C:\copyFile.bat" was the first sign it was for Windows only...

    One tester at my last job actually created a file called /home/username/c:\My%20Documents\foo\bar or something similar on a unix system. Evidently the : makes it easier to create that than it is to delete it.

  • dkf (unregistered) in reply to Packrat
    Packrat:
    Have I missed anything else?
    You missed the fact that the code to create the batch file is using getAbsolutePath() internally too, even though it's totally not necessary at that point. Needless obfuscation, here we come!
  • Maks Verver (unregistered)
    Nojazz Song Hurts:
    it has a tidy API, only a couple of obvious bugs (for example: someone could re-write that batch file to do something different), and it's a great hack!
    You must be kidding?!
    sure, it's named wrong: it should be something like 'copyThenDeleteOriginal', but that's not much of a WTF.
    The name should rather be "MoveOrCopyOrDelete" because given a pair of arguments, it may at random do one of (1) move the file (if everything succeeds) (2) copy it (if permissions allow the original file to be read, but not deleted) (3) just delete the source (if copying fails for some reason).

    Furthermore, it doesn't report to the caller what actually happened. Maybe the file will have been moved. Maybe it was deleted. Who knows? The function is not going to tell you.

    Basically this function plays Russian roulette with your filesystem. That qualifies as a "tidy API" to you?

    so what if it is not system independent, but not everyone needs that.
    Agreed, but then it's still stupid to do this via a batch file (which needlessly changes directories, and introduces a privilege escalation attack) making the whole procedure vastly more complex and error-prone (for example, now you need write privileges on C:\ to copy a file on a different disk, even though there may well be no C:\ partition at all). Let alone the introduction of additional shell escaping bugs.

    Finally, the code eats up any exceptions that are thrown (instead of handling the exceptions relevant to the operation being performed), which is in itself a deathly sin for a serious Java programmers.

    How this code leaves you speechless is beyond me.
    Assuming you work as a software developer: if you care at all about the credibility of the software industry, please do us a favor and choose another line of work. Or, alternatively, send a random sample of your work to alexp-at-WorseThanFailure.com.
  • hello (unregistered)

    i think no one guessed the problem of deleting the source: my try is, the guy intended to delete the batch file and fucked up. this makes sense!

  • Cloak (unregistered) in reply to Alex
    Alex:
    Another cool feature is that it will only "work" one time on any given PC, since it doesn't overwrite the batch file it already exists, so it just keeps running the first batch file ever created by the method. Genius!

    The batch file contains this:

    cd
    copy %1 %2

    This means that there are variables. Once the batch is created it can be used to copy whatever you like. The real WTF is

    File batchFile = new File("C:\copyFile.bat"); if (!batchFile.exists()){

    After the file is created he checks if it exists and if it does not exist than he attempts to write to it??? On the other hand after

    File batchFile = new File("C:\copyFile.bat");

    the batch file should always exist and then nothing is written to it and it remains empty???

  • hello (unregistered)

    btw, i've come up with two trollish quotes!

    Write once, crawl like a turtle everywhere!

    and:

    Write once, collect garbage everywhere!

    i'm so proud of myself! :)

  • (cs) in reply to tobjar
    tobjar:
    "Brillant!" is the word you're searching for, I'm sure.

    stick to coding, dude. leave the copy editing to people who know how shit is spelled.

    Whoooooooooooooooosh...

    http://en.wikipedia.org/wiki/Inside_joke

  • Enrique (unregistered) in reply to Cloak
    Cloak:
    The real WTF is

    File batchFile = new File("C:\copyFile.bat"); if (!batchFile.exists()){

    After the file is created he checks if it exists and if it does not exist than he attempts to write to it??? On the other hand after

    File batchFile = new File("C:\copyFile.bat");

    the batch file should always exist and then nothing is written to it and it remains empty???

    The File class in Java is used to represent a file or directory in the filesystem. It doesn't have to exist; think of it as a pointer to a file, which you can use later for file-related operations, like checking if the file actually exists, or if it's a directory, if it can be read, or written to, etc. So new File("x") doesn't create the file x in the filesystem, it just creates an instance of File.

    The real WTF are the people defending this piece of shit code, which could be considered the equivalent of SQL injection at the operating system level. There are so many ways to do evil stuff on a system that is running that code...

  • SomeCoder (unregistered)

    Is it just me, or are the CodeSOD WAY better than the regular WTF articles?

    This one just... I...

    My eyes! The goggles do nothing!!

  • (cs) in reply to Cloak
    Cloak:
    Alex:
    Another cool feature is that it will only "work" one time on any given PC, since it doesn't overwrite the batch file it already exists, so it just keeps running the first batch file ever created by the method. Genius!

    The batch file contains this:

    cd
    copy %1 %2

    This means that there are variables. Once the batch is created it can be used to copy whatever you like. The real WTF is

    File batchFile = new File("C:\copyFile.bat"); if (!batchFile.exists()){

    After the file is created he checks if it exists and if it does not exist than he attempts to write to it??? On the other hand after

    File batchFile = new File("C:\copyFile.bat");

    the batch file should always exist and then nothing is written to it and it remains empty???

    Umm, do you understand Java? new File("somefile"); does not create a new file if it does not exist: it creates a File object that may or may not point to an actual file.

  • Anon (unregistered) in reply to Enrique
    Enrique:
    The File class in Java is used to represent a file or directory in the filesystem.
    Actually that's another really good Java WTF. A File isn't a File: it's a Path. If you want an object that actually represents a file, you'll need RandomAccessFile.

    File is just an abstract path. Why not call it "Path" then? It's Java. It doesn't have to make sense.

  • Thomas (unregistered) in reply to Anon
    Anon:
    ailivac:
    The true WTF is that Java doesn't have a standard or sane way of installing extra libraries, so programmers have to reinvent broken wheels like this all the time.
    It does have a standard way - it just isn't sane. Assuming %JRE_HOME% is the JRE directory, you "simply" copy the JAR library into %JRE_HOME%\lib\ext.

    Things get really fun when you install the JDK, since it happily installs two copies of the JRE: on embedded next to the compiler and utilities, and one "normal" JRE. Why the two copies? It's Java. It doesn't have to make sense.

    "It's Java. It doesn't have to make sense." Now, this has got me a nice laugh.

  • Mainc Mailman (unregistered) in reply to Anon
    Anon:
    It's Java. It doesn't have to make sense.

    Forget it, Jake. It's Javatown.

  • (cs) in reply to tobjar
    tobjar:
    "Brillant!" is the word you're searching for, I'm sure.

    stick to coding, dude. leave the copy editing to people who know how shit is spelled.

    Feel clueless yet?
  • segmentation fault (unregistered)

    this code is amazing.

    can someone please tell me if anyone anywhere has ever written decent java? its gotta be possible, right?

  • (cs)

    While learning VisualBasic (way back when), I wanted to be able to generate a list of files in a directory.

    I spent three days learning the language, hacking the code and slugging my way through it (I wasn't a very good programmer back then).

    When I showed it to my friends, I discovered that I had rewritten "dir /b" in VB. And it only took me three days.

    doh

    -- Seejay

    Edited to add: Yes, I knew what dir was, but I didn't know about the /b. I wanted the list of files without all the extra stuff.

  • Andy Janata (unregistered) in reply to Look at me! I'm on the internets!
    Look at me! I'm on the internets!:
    Anything wrong with:

    process.exec("copy file1 file2"); // windows

    You could add a System.getProperty("os.name") and make it universal.

    Of course, I'd probably want to uses an abstract factory to do this -- It's much more enterprisy.

    I'm not 100% sure on this, but I believe "copy" is an internal to the command interpreter, so you would have to cmd /c copy file1 file2 (or command /c if you want to have 9x support.) :)

  • (cs) in reply to snoofle
    snoofle:
    I haven't head the pleasure that is Vista yet - is it really that bad?!
    It's definitely not a pleasure.
  • (cs) in reply to tobjar
    tobjar:
    "Brillant!" is the word you're searching for, I'm sure.

    stick to coding, dude. leave the copy editing to people who know how shit is spelled.

    This site officially died.

    ...with me

  • (cs) in reply to hello
    hello:
    Write once, collect garbage everywhere!

    I work in J2ME, so I'm going to have to disagree with the second one; it's more like 'write once, maybe it'll collect garbage when it feels like it, more likely, it'll just powercycle your phone'.

    Addendum (2007-08-03 12:36):

    hello:
    Write once, collect garbage everywhere!

    I work in J2ME, so I'm going to have to disagree with the second one; it's more like 'Write once, maybe it'll collect garbage when it feels like it, maybe. More likely, it'll just powercycle your phone'.

    Actually, it's more like 'Write once, then write again to work around a weird glitch on a non-compliant runtime, then rewrite again because the original was designed for a smartphone and creates a million threads on startup, it now needs to run on a 'free-with-contract' phone, etc.'

  • rd (unregistered) in reply to Someone You Know
    Someone You Know:
    rd:
    bkendig:
    Jim:
    sure, it copies, but then it deletes the source!

    So, just copy it back then!

    Brilliant!

    "Brillant!" is the word you're searching for, I'm sure.

    Douche! er, sorry, make that Touche!

  • Shadow Wolf (unregistered) in reply to SuperousOxide
    SuperousOxide:
    ailivac:
    Plenty of languages don't have built-in routines to do high level operations like copying files, but most have libraries available to do it (such as Perl's File::Copy).

    But Java is not a language that normally shies away from providing high level functionality in its standard libraries.

    In fact, Java's standard library provides File.renameTo(). No need for an additional library.

  • matthew (unregistered) in reply to Ben

    Actually, it does.

    FileChannel has a transferTo and transferFrom methods that do a copy without moving the actual data to user space - provided the OS supports it of course.

    The real WTF is always to not know your tools.

  • (cs)

    Guys, you're missing one of the most obvious problems of all - if the destination file already exists, the program will hang forever on the overwrite prompt!

    "Overwrite destfile? (Yes/No/All): "

  • Grant (unregistered) in reply to rd

    Paula!

  • Grant (unregistered) in reply to rd
    rd:
    bkendig:
    Jim:
    sure, it copies, but then it deletes the source!

    So, just copy it back then!

    Brilliant!

    Paula!

  • AdT (unregistered) in reply to Packrat
    Packrat:
    It won't work on *nix or, I presume, on the Mac.

    Mac is *nix these days. :-D

    Anyway, it won't work on the Mac - there are no batch files though maybe the next version of his kind of copyFile will support AppleScript, or /bin/sh ... ;-)

    Packrat:
    It'll die horribly if either the source or destination names have spaces in them.

    No, why would it? The batch file doesn't even contain any check on the number of arguments. So it'll just try to copy the wrong file to the wrong destination, e.g. if the source file name is "c:\Documents and Settings\EveryoneMustBeAdmin\My Documents\Important.doc", it'll try to copy "c:\Documents", whatever that is, to "and", and ignore all further arguments. Very likely this will fail with an error code, but the exit code of the process is not tested. Then it goes on and deletes the source file (this WILL work provided the permissions are ok).

    So if the source file name contains spaces, this is more like "delete" (another major WTF right there). If the destination file name contains spaces but the source file name does not, the file may be moved, but not to the expected destination.

    One final WTF: If one is to perform a move, one should absolutely try to use the functions the OS provides for this purpose. You don't want to copy a multi-gigabyte data file just in order to rename it or move it to a different directory on the same filesystem. As another user pointed out, Java has a File.renameTo method for this purpose.

  • (cs) in reply to Ant
    Ant:
    Hey now, you've got to give the guy _some_ credit: this would execute faster than Vista's built in copy routine.

    In what possible way would creating a batch file to call Vista's built in copy routine be faster than just calling it directly?

    Besides, Vista's copy uses the exact same NTFS 3.1 copy function that XP does. http://en.wikipedia.org/wiki/NTFS

    If you really feel the need to mock Vista, there are plenty of easy, legitimate targets. Try picking one of those next time.

  • Harry (unregistered) in reply to snoofle
    snoofle:
    Ant:
    Hey now, you've got to give the guy _some_ credit: this would execute faster than Vista's built in copy routine.
    I haven't head the pleasure that is Vista yet - is it really that bad?!

    Microsoft says it'll leave you speechless... as Alex was by this codeSOD.

  • (cs)

    Wow, that was amazing.

    I do admit, the Java classes are not totally obvious and it takes a couple of years to really learn how to get the most out of them. Some things which should be simpler in Java are not. For example, there should be a writeTo() method in streams, so you could do:

    InputStream input = new FileInputStream(...); OutputStream output = new FileOutputStream(...); input.writeTo(output);

    which would read the entire input to the output and then close everything, because that's the most common usage of files. But there isn't such a method so you need to write a loop with a buffer. It's obvious when you know it, not obvious when you don't.

    But anyway that code could cause brain damage.

  • Benjie (unregistered) in reply to Jim
    Jim:
    Anyone notice that this moves the file, instead o0f copying?

    sure, it copies, but then it deletes the source!

    sarcastic clap

    IE does the same thing when you download files

  • (cs)

    I once did the opposite... I made a shell script that generated Python code with sed, grep, read, echo, ls & etc. A Python script executed the shell script with command.getoutput(command) and then executed the generated Python code with exec(code).

    This was all out of laziness :)

  • The Masked Director of Development (unregistered)

    Breathtaking.

  • ffff (unregistered)

    This had to be 100% intentional. The combination of knowledge displayed & method of execution points to a sick man making a sick joke. bravo

  • M.G. (unregistered) in reply to JavaCoder
    JavaCoder:
    Wow, that was amazing.

    I do admit, the Java classes are not totally obvious and it takes a couple of years to really learn how to get the most out of them. Some things which should be simpler in Java are not. For example, there should be a writeTo() method in streams, so you could do:

    InputStream input = new FileInputStream(...); OutputStream output = new FileOutputStream(...); input.writeTo(output);

    which would read the entire input to the output and then close everything, because that's the most common usage of files. But there isn't such a method so you need to write a loop with a buffer. It's obvious when you know it, not obvious when you don't.

    But anyway that code could cause brain damage.

    File sourceFile = new File(...);
    long fileSize = sourceFile.length();
    ...
    FileInputStream input = new FileInputStream(...);
    FileOutputStream output = new FileOutputStream(...);
    inputChannel = input.getChannel();
    outputChannel = output.getChannel();
    long transferSize = inputChannel.transferTo(0, fileSize, outputChannel);
    if (tranferSize != fileSize) { // Didn't transfer the while file, do something about it here }
    // Sorry, you still have to close things yourself...
    

    Does that help?

  • screwd (unregistered) in reply to Alex

    Um? It will continue to work after the first time, since it just writes a batch file that says copy %1 %2.. I don't see how this will cause it to only work once?

  • (cs) in reply to M.G.

    Ah yes, I should remember to always use FileChannels for this type of thing. Most of what I do is to and from network, not from file to file, so I don't have occasion to use FileChannels too often. And when I do read a file it's usually from within a webapp that I'm writing which means I need to use getResource(), because the file I'm looking for may not even be a file (ie, it could be a resource in a zip or who knows what).

    But you're totally right, that's exactly the best and fastest file copy idiom in Java. Depending on implementation, that copy could be done without the bytes even needing to be brought into memory I guess?

  • SomeCoder (unregistered) in reply to segmentation fault
    segmentation fault:
    this code is amazing.

    can someone please tell me if anyone anywhere has ever written decent java? its gotta be possible, right?

    I think I might have written some decent Java once... maybe...

    Nah, probably not :)

  • (cs) in reply to Aaron
    Aaron:
    I'm quite impressed. First it makes a call to a parameterless method which tries to create a batch file in a hard-coded location which might very well not have write permission, opens the file twice (write, then append), doesn't trap any exceptions, doesn't quote the file names, and only does this if the file doesn't already exist (doesn't care if it was modified). Then it launches the batch file as its own process regardless of what might be in it, checks for the existence of the source file after attempting to copy it, deletes the source file even if the source and destination were the same, and essentially eats any exceptions during the "copy" process (but would still throw exceptions encountered during the batch file creation). And on top of this, is named copy when it clearly moves.

    The best part though, is that somebody has already written a FileIO class that could probably do this in two lines - we don't know that it has a readFile method, but it definitely has a writeFile.

    My Java's just a bit rusty but I think I count no less than 10 different errors. It's very Agile though, I'll give them that. Way to think outside the process... er, box.

    No, the "programmer" is clearly not thinking outside the box. Otherwise there'd be a TCP connect to a replication server, possibly using XML to specify the destination, followed by a copy back from the replication server to the destination directory. (Now, that's enterprisey (c).)

    This, I believe, is what Java calls "reflection."

    ducks

  • (cs) in reply to Anon
    Anon:
    ailivac:
    The true WTF is that Java doesn't have a standard or sane way of installing extra libraries, so programmers have to reinvent broken wheels like this all the time.
    It does have a standard way - it just isn't sane. Assuming %JRE_HOME% is the JRE directory, you "simply" copy the JAR library into %JRE_HOME%\lib\ext.

    Things get really fun when you install the JDK, since it happily installs two copies of the JRE: on embedded next to the compiler and utilities, and one "normal" JRE. Why the two copies? It's Java. It doesn't have to make sense.

    And don't forget that if you use competing IDEs/frameworks/products in general from Sun/IBM/Borland/anyone, you tend to end up having a different $JRE_HOME for each one, because they're not compatible.

    This isn't a whiny comment along the lines of "Hah! It's supposed to be a WORE Universal System!" It isn't even a comment on the fact that, at bottom, the philosophy of the whole JVM is pretty much command-line based, and Unixy at that. I like Unix command-lines (though not Unix environment variables.)

    I'd just rather have some consistency. Even if that means a benevolent Java dictator. And even if that benevolent Java dictator is Sun.

    And you're absolutely right. It's very far from sane. Maybe 20 year olds can remember this crap, but us 45 year olds are staring into the abyss of Alzheimers...

  • Legion (unregistered)

    Remind me of the secretaries where my dad work. When they needed to copy a document on a floppy they would open it in word and use 'save as'

  • Andrew (unregistered) in reply to Kittown
    Kittown:
    This is a pretty bad implementation of a pretty legit idea. Sometimes you HAVE to use batch files to do those things from java to make the result more predictable and less dependent on particlar jvm problems. In some cases this helps to speed up the file copying procces by 2-5 times or so comparing to common file copying methods from Apache Ant. There is usually more that one command in that batch, though, and there are all kinds of symbol quoting code, as well as checks for the system this is used on.

    There is never a good excuse to use Runtime.exec(). If the task is large enough, then use IPC, or client/server between Java and the native program. Why spawn a new process to move a few files?

    If you have to call native OS commands, then use JNI. Write real Java classes to do FileSystem.rename('myfile.txt'); or whatever. Only the shared libraries or DLLs are non-portable.

    I can write a clean rename-file that is faster than a second shell process (or thread, whatever Windows does). The JNI C code is general-use, and not much more work.

    Oracle's JDBC driver uses JNI to call their OCI library. No one notices, since to Java its just JDBC. Rewriting OCI in pure Java isn't needed.

  • (cs) in reply to Maks Verver
    Maks Verver:
    Nojazz Song Hurts:
    it has a tidy API, only a couple of obvious bugs ... <snip> How this code leaves you speechless is beyond me.
    Assuming you work as a software developer: if you care at all about the credibility of the software industry, please do us a favor and choose another line of work. Or, alternatively, send a random sample of your work to alexp-at-WorseThanFailure.com.
    To be absolutely fair to an unregistered and therefore fleeting coward, he/she/it is by inference from the number of comments entirely correct.

    Well, at least in the bits that I didn't snip; if, by "a couple" hsi means, in that lazy common parlance that we have all grown to know and love, "up to and beyond a hundred comments of varying length." Hardly speechless.

    In the sort of balance that Fox News demands, I should also point out that you are also entirely correct. Many people complain about the ignorance of Java programmers, but -- ignoring the ignorance of the Ant-farmers in the Apache community -- I am not one of them. A professional Java programmer is just as good as any other professional programmer, on average, and since most CompSci graduates these days can program in Java, that means that there are a lot of them about. I suspect that Maks might, perhaps, on balance, and without prejudice and with all due deference, be a total twat.

  • Ant (unregistered) in reply to damncrackmonkey
    damncrackmonkey:
    Ant:
    Hey now, you've got to give the guy _some_ credit: this would execute faster than Vista's built in copy routine.

    In what possible way would creating a batch file to call Vista's built in copy routine be faster than just calling it directly?

    Besides, Vista's copy uses the exact same NTFS 3.1 copy function that XP does. http://en.wikipedia.org/wiki/NTFS

    If you really feel the need to mock Vista, there are plenty of easy, legitimate targets. Try picking one of those next time.

    I'm going to assume you haven't had the pleasure of copying files on Vista yet. The 'copy' in command prompt is the actually command that does th copying, yes, I believe it is so. However, when you copy files using explorer in Vista (you know, drag/drop, Ctrl+C/Ctrl+V, etc), I've no idea what Windows (in general) uses, but apparently it has a wrapper around 'copy', or maybe a separate routine altogether (that dialog it show how much time remains..). In XP it was fine. Vista, OTOH, takes ages to copy a single file. The command line 'copy' command is almost instant. My gut feeling is that Vista does some checking for file sizes, best copy block size of some sort, etc. And this is taking it forever.

    Next time, do your research before bashing other replies like that.

  • (cs) in reply to real_aardvark
    real_aardvark:
    No, the "programmer" is clearly not thinking outside the box.
    But arguably should be put back into it as quickly as possible.
  • (cs) in reply to gwenhwyfaer
    gwenhwyfaer:
    real_aardvark:
    No, the "programmer" is clearly not thinking outside the box.
    But arguably should be put back into it as quickly as possible.
    What; and wrapped up with a nice pink bow and sent to <pick company of one's choice here> as Chief Architect?

    I've gotta say, I've seen a lot of stupid comments on this site. And only 90% of them are mine. (Memo to self: lay off the steroids. Or at least Bracknell.) But this one is a peach.

    (And by "this one," I mean "NoJazz's." Duh!)

  • anonny (unregistered) in reply to Ant
    Ant:
    However, when you copy files using explorer in Vista (you know, drag/drop, Ctrl+C/Ctrl+V, etc), I've no idea _what_ Windows (in general) uses, but apparently it has a wrapper around 'copy', or maybe a separate routine altogether (that dialog it show how much time remains..). In XP it was fine. Vista, OTOH, takes ages to copy a single file. The command line 'copy' command is almost instant. My gut feeling is that Vista does some checking for file sizes, best copy block size of some sort, etc. And this is taking it forever.
    It uses a combination of COM and the already-ridiculed "allocate a buffer, do a read, do a write" pattern. It's done like this so that Vista can show the exact byte progress and copy speed of the operation.

    Of course, that's much slower than having NTFS do the copy, especially because it involves COM invocations.

  • (cs) in reply to ailivac
    ailivac:
    Ben:
    Volmarias:
    Java doesn't actually have an OS-level file copy method that can be called (you have to actually read in the file and write it out to a new file!)

    This, of course, is the real WTF!

    Plenty of languages don't have built-in routines to do high level operations like copying files, but most have libraries available to do it (such as Perl's File::Copy).

    The true WTF is that Java doesn't have a standard or sane way of installing extra libraries, so programmers have to reinvent broken wheels like this all the time.

    Although java is pretty much made of libraries anyway - all those classes aren't really 'part of the language'. It's just a wonder that nobody at Sun has added a utility class like that to the standard java library given that it's so bloated with everything else...

Leave a comment on “My Kind of copyFile”

Log In or post as a guest

Replying to comment #:

« Return to Article