Best way to see if a URL to filesystem file exists?

What's the best way to test if a file (specified by a URL) exists? I know if I had a file object, I could just do: new File( path ).exists() but File takes a URI not a URL as a constructor param. If it's a file, I can just do this, right?:
try
     InputStream in = url.openStream();
     in.close();
catch (IOException e)
     //Assume doesn't exist?
}But if it's a jar file, that won't work since you can only open a stream to an entry. So for jar files, I do this, right?
try
     URLConnection conn = url.openConnection();
     if ( conn instanceof JarURLConnection ) ( ( JarURLConnection ) conn ).getJarFile();
catch (IOException e)
     //Assume doesn't exist?
}Is there a better way?

Hi,
Try the below method which convert the given URL to and check if the file exists
public boolean isFileExistGivenURL (URL url) {
          if (url == null || !url.getProtocol().equals("file")) {
            return false;
        } else {
            String filename = url.getFile().replace('/', File.separatorChar);
            int pos =0;
            while ((pos = filename.indexOf('%', pos)) >= 0) {
                if (pos + 2 < filename.length()) {
                    String hexStr = filename.substring(pos + 1, pos + 3);
                    char ch = (char) Integer.parseInt(hexStr, 16);
                    filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
            return new File(filename).exists();
        }Hope this helps
Regards,
Alan Mehio
London,UK

Similar Messages

  • Best way to remove last line-feed in text file

    What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
    (as echo -n will remove all trailing newline characters)

    What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
    (as echo -n will remove all trailing newline characters)
    According to my experiments, you have removed all line terminators from the file, and replaced those between lines with a space.
    That is to say, you have turned a multi-line file into one long line with no line terminator.
    If that is what you want, and your files are not very big, then your echo statement might be all you need.
    If you need to deal with larger files, you could try using the 'tr' command, and something like
    tr '
    ' ' ' <file.txt >newfile.txt
    The only problem with this is, it will most likely give you a trailing space, as the last newline is going to be converted to a space. If that is not acceptable, then something else will have to be arranged.
    However, if you really want to maintain a multi-line file, but remove just the very last line terminator, that gets a bit more complicated. This might work for you:
    perl -ne '
    chomp;
    print "
    " if $n++ != 0;
    print;
    ' file.txt >newfile.txt
    You can use cat -e to see which lines have newlines, and you should see that the last line does not have a newline, but all the others still do.
    I guess if you really did mean to remove all newline characters and replace them with a space, except for the last line, then a modification of the above perl script would do that:
    perl -ne '
    chomp;
    print " " if $n++ != 0;
    print;
    ' file.txt >newfile.txt
    Am I even close to understanding what you are asking for?

  • How is the best way to backup and organize Adobe layered .PSD files on iMac OSX maverick?

    How is the best way to organize and backup Adobe layered PSD files on iMac desktop OSX maverick?
    I lost all my Adobe Photoshop files + everything else on my IMAC when it crashed. They reinstalled Operating System.  But now i must install programs such as MS Word & Adobe indesign suite.
    Please help me determine what is the bestway to backup Adobe layered  PSD files? I believe these are my choices to be assured this doesn't ever hapen again. Please comment.
    Buy Apple Airport Time capsule $280.  But I am not sure if it can store PSD layers. Can it or do you have to have Apple Apperture  software to act be sure layers are saved
    I had had trouble getting Adobe Cloud to sync to save files and so just trusted my computer to not ever crash.  Any hints on this procedure
    Are there any hints on PhotoShop image organization for a current IMac usser ?
    Please help.
    Teann  ucreateit

    My backup plan is to use Time Machine to make a backup to an external disk drive plus I also do a clone of my system disk. So far between the bootable clone and the Time Machine backup this plan has covered all of my needs.
    Allan

  • Whats the best way to transfer all my pic and vid files from Mac Air to back up drive to free up space on hard disk?

    whats the best way to transfer all my pic and vid files from Mac Air to back up drive to free up space on hard disk?

    Get a third drive if needed, open the Time Machine pane of System Preferences, set it not to exclude that drive, and drag the files to it. If you're moving an iTunes or iPhoto library, launch the application with the Option key held down and choose the moved library.
    (118789)

  • What is the best way to use wi-fi to transfer pdf files from an ipad to a mac mini, not using an internet, just wi-fi.

    What is the best way to use wi-fi to transfer pdf files from an ipad to a mac mini, not using an internet, just wi-fi?

    If the Mac use Lion (10.7) you can use Airdrop for that.
    With Mac's not using Lion you may set up a computer to computer (ad hoc) connection.
    How to --> http://docs.info.apple.com/article.html?path=Mac/10.6/en/8339.html
    Lupunus

  • What is the best way to pass the web url of a link embedded in a PDF document?

    I have a WPF app in which is hosted an instance of axAcroPDF. I've included it via a System.Windows.Forms.UserControl that is a child of a System.Windows.Forms.Integration.WindowsFormsHost.
    The PDF Document is essentially a flow chart in which there are links that are currently set to open a webpage by url. When the links are clicked in a standard adobe Acrobat X application they work fine, however when they are clicked within the WPF application's axAcroPDF component nothing happens. Furthermore I have also on another tab within my app a System.Windows.Controls.WebBrowser on which I would like the linked url's to be opened. I need to construct a method, event listener and event handler so that when the link in the pdf file is clicked in the axAcroPDF object the url is passed to a method that will call System.Windows.Controls.WebBrowser.Navigate() passing it the url as an argument. I've saught help within the WPF developer community and got some advice to use the "execute a javaScript" link behavior to call a method within my WPF app passing it the url as a string argument, but have been unable to implement this within my code. I click the link with the javascript but it does not result in a method call of the method in my WPF app. Can anyone help me with possibly a more simple way to just listen for the event that already exists with the "open a web link" action?
    Thanks for any help,
    Matthew

    Moved to Acrobat SDK

  • Best way to record 50 kS/s data to file

    I am trying to read data from a DAQ at a sampling rate of 50 kS/s and record it to a file. My application needs to run for at least a few hours. Initially, I tried a producer-consumer loop pattern with a Write to Measurement File Express VI, but it wrote the data too slowly, and my queue filled up. Now I am trying to use the Write to Spreadsheet File VI with or without a producer-consumer loop pattern (see attached VIs). Both seem to write data to file, but neither writes the number of datapoints I would expect (both have far fewer datapoints).
    What is the best way to write this data to file? This seems like a basic question, so if it has already been discussed at length in another forum, or if there are examples of it which someone could direct me to, that would also be appreciated.
    Thank you!
    Solved!
    Go to Solution.
    Attachments:
    Record Data 8-7-13 with Producer Consumer.vi ‏54 KB
    Record Data 8-7-13 without Producer Consumer.vi ‏48 KB

    I agree that TDMS is probably the best way to go for fast data streaming.
    I also want to point out that you can read TDMS files with some spreadsheet software. This makes it easier to manage and provides a method for human readability.
    Add in tool for Open Office Calc
    http://www.ni.com/white-paper/6849/en
    Add in tool for MS excel
    http://www.ni.com/white-paper/4906/en
    Jeremy P.
    Applications Engineer
    National Instruments

  • Best way to have multiple arrangements in one project file?

    Hello everybody,
    I am trying to figure out a smart way of having multiple arrangements associated with one project. More importantly, this would allow me to have multiple arrangements associated with the same pool of audio files in one audio window -- without needing to import/export audio.
    In DP this is achieved with multiple "sequences". I am aware this feature is not in Logic. However, perhaps there is a way to achieve a similar process?
    I guess a not-so-elegant approach would be to simply save a new song; however, if I want to use new song audio files in the old song, i'd have to import the new song audio files to the old song. Not a big deal, I guess.
    Thanks,
    D
      Mac OS X (10.4.5)  

    Thanks for responding Justin & David,
    Let me to try to better explain what I am trying to achieve.
    (Currently my problem is that I am thinking in the "workflow language" of DP, trying to figure out an analogous "translation" in Logic. For those familiar with DP, I am simply wanting to create a new sequence, within the same "song" file.
    Let's say I create a bunch of audio tracks, and compile them into arrangement A. I would like to work on a new idea that may be part of the final piece; So, I would like to have a clean, new arrangement page where I can put some of the previous audio files generated & used in arrangement A, as well as make some new ones. I'll call this arrangement B. So, in other words, arrangement B is a fresh new arrangement page that uses audio files from arrangement A as well as new ones.
    If any previous/current DP users know the best way of approximating DP's use of multiple sequences, I'd love to know what you do.
    I will explain what I am able to do if I were in DP (for the sake of communicating my problem, but not intended to begin a DP vs. LP thread).
    I will use Logic terminology, but DP concept:
    In DP, one can have multiple Arrangement windows that share a pool of audio files from one Audio Window. This allows one to try different arrangements, without keeping track of new/old audio files; and without needing importing and exporting them between songs.
    I have been reading the Project Manager section in the Logic manual. (By the way, I am not seeking a DP functionality in Logic; I am seeing how one achieves a similar workflow approach in Logic.)
    I realize I cannot even explain myself well. Perhaps I should consider the concept of sub-arrangements, and master arrangement. I guess, sub-songs, and work-in-progress master song. The master songs should have all audio files, and sub-songs have whatever audio files were created while working on that particular sub-song. So, with this, whenever I want to go back to master song, I've got to import the audio files from the sub-song.
    This may make sense - & may work smoothly. I've got to try it out.
    (Btw, David, I captured a screen shot, but I don't know where/how to post it.)
    A major thanks to all who have the patience to read so many words for a one word sentence.
    Thanks,
    Danny

  • Best way to burn photos on DVD as data files?

    Ok - I may be losing it, but I'm confused as to best way to burn a DVD of photo files that I just want to be photo files - not played in a slideshow, etc. Basically, I scanned 50+ photos and used them in a montage I created in Photo To Movie. But, I want to give the client two discs - one that is the TV-ready playable DVD - did that one already. Second is a DVD (or CD?) that they can put in their computer and just get the files off if they ever want to use them (since I'm charging them for scanning and retouching the vintage photos).
    Can someone please let me know how to do it? All told it's about 63 photos and 80 MB according to iPhoto Album. So, do I use DVD or CD or does it matter? How do I transfer (drag and drop)? and Burn?
    Thanks -
    Alexa

    Alexa:
    To burn a data disk of the photos you used in the slideshow you need to export them to a folder on the Desktop via the File->Export->File Export menu option. Select the appropriate options for exporting and export.
    Then drag that folder onto a mounted blank disc and burn via the Finder. That will give you a cross platform disk of just the image files.
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto (iPhoto.Library for iPhoto 5 and earlier) database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've created an Automator workflow application (requires Tiger or later), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. It's compatible with iPhoto 6 and 7 libraries and Tiger and Leopard. Just put the application in the Dock and click on it whenever you want to backup the dB file. iPhoto does not have to be closed to run the application, just idle. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.
    Note: There's now an Automator backup application for iPhoto 5 that will work with Tiger or Leopard.

  • What is the best way to get PATHS from one Photoshop psd file to another?

    Hi! New on the site, and I signed up specifically to ask the best way to import one .psd file into another, including the paths on the paths palette.
    Almost all of my Photoshop drawings make heavy use of vector paths, which I then stroke using using PS natural-media brushes and the "stroke paths" function (usually with "simulate pressure" checked.) Also, my .psd files tend to be, um, HUGE... and I typically break up a whole drawing into separate PS files and then assemble all of them into one final finished graphic.
    I have no trouble moving raster stuff from file to file. Just put all the layers I want to transfer into a group and drag the group to the other .psd. Works fine, including layer masks. But I have not found a good way to get vector paths from the Paths palette of one .psd to another. Of course I can select paths and copy them to the Win clipboard, switch to the other .psd, and paste them back in. The drawback to that method is that I lose the correct size relation between the results of previously done "stroke paths" operations (on raster layers) and the paths that generated them. Sometimes the copied-in paths are way too large, sometimes way too small, never Just Right.
    As I'm sure most of you know, if you resize an entire Photoshop document from within PS, any paths it contains are correctly resized along with everything else. That's no longer true after grouped raster layers are dragged over to another document but paths are copied and pasted in. The size connection is lost. (Location placement, too.)
    I WANT those paths! After I bring a piece of a drawing into the full final drawing, what looked good when I was working on it separately often doesn't look right any longer and I want to re-stroke those paths using different brush diameter, opacity, etc., or maybe even a completely different brush.
    I've tried bring outside .psd files in as smart objects with the Place command but either that doesn't work or I'm not doing it right. Using Place, the paths in the Placed document don't come in at all.
    I'll be very grateful for any hints or strategies any of you knowledgeable folks can give me. Thanks very much!
    Jim
    Note, PS CS3 extended on Win 7 pro.

    Denny
    1. Connect the two macs - firewire, ethernet, sneakernet as suits you - and copy the iPhoto Library Folder from Old Machine to New Machine. Drag it from Home/Pictures to the same location on the new machine.
    2. Because all the files 'belong' to the account on the old machine, you have to update the file permissions: hence Download BatchMod from
    http://macchampion.com/arbysoft/
    And apply it to the iPhoto Library Folder using the settings found here:
    http://homepage.mac.com/toad.hall/.Pictures/Forum/BatChmod.png
    (Credit to Old Toad for this one).
    Note: This must be run on the new machine after copying the files over.
    3. Then launch iPhoto on the new machine.
    Regards
    TD

  • Flex/AS3 Best way to construct a derived class instance from an existing base class instance?

    What is the best way to handle the instantiation of a derived class from an existing base class.
    I have a base class which is being created via remote_object [RemoteClass alias] from the server.   I have other specialized classes that are derived from this baseclass, but serialization with the server always happens with the base class.     The base class has meta data that defines what the derived class is, for example
    [RemoteClass (alias="com.myco...')]
    public Class Base
         public var derivedType:String;
         public function Base()
    public Class Derived extends Base
         public "some other data"
         public function Derived()
    In my Cairgorm command which retrieves this object from ther server I want to do this:
    public function result (event: Object):void
        var baseInstance:Base = event.result;
         if (baseInstance.derivedType = "derived")
              var derivedInstance:Derived = new Derived( baseInstance );
    What is the most efficient way of doing this?   It appears to me that doing a deep-copy/clone and instantiation of the derived class is pretty inefficient as far as memory allocation and data movement via the copy.

    Thanks for the assistance.  Let me try to clarify.
    MY UI requires a number of composite classes.    The individual components of the composite classes are being transfered to/from the server at different times depending upone which component has changed state.    The construction of the composite classes from the base class happens in my clients business logic.
    Composition happens in a derived class; but server syncronization happens using the base class.    When I recieve the object from Blazeds through the remote object event, it is in the form of the base class.  I then need to instantiate the derived class and copy the elements of the base class into it (for later composite construction).   And likewise when sending the base class back to the server, I need to upcast the derived class to its base class.   But in this case just a mere upcast does not work.  I actually need to create a new base class and copy the attrbutes into it.  I believe this is limitation of how remoting works on Flex/AS3.
    My question is, what is the best way to turn my base class into it's derived class so further composite construction can take place.   The way I am currently doing it is to create a  load method on the base class, that takes the base class as on argument.  The load function, copies all of the instance attribute references from the base class to the target class.
    public Class Base
         public function Base()
         public function load(fromClass:Base)
        {  //  copy the references for all of the instance attributes from the fromClass to this class }
    Then,  after I recieve the base class from the server.   I create a new derived class and pass the base class into the load function like this:
                for (var i:int=0; i < event.result.length; i++) {
                    var derived:Derived = new Derived();
                    derived.load(event.result[i]);
    The drawbacks of this approach is that it now requires 2 extra instance creations per object serialization.   One on recieving the object from the server and one sending it to the server.    I assume copying references are pretty efficient.  But, there is probably some GC issues.     The worst of it is in code maintenance.   The load function now has to be manually maintained and kept in sync with the server class.
    It would be interesting to hear how others have solved this problem.      The server side is an existing application with around 2M LOC, so changing the code on the server is a non-starter.
    Thanks for your help.

  • Best way to insert 300dpi photo's into Ilustrator file for print

    I am creating a 5.5 X 8 postcard style card for print.  I need to place 15 photographs that are aprox. 1.5 X 2.5 each.  What is the best way to insert these files so that my file doesn't become too large?  I will be making a PDF of the final artwork to send to the printer.  Your guidance is much appreciated!!

    Link don't embed the images. Use a layered format such as .psd, .tif, or .pdf. Psd is not lossy, .tif can be lossy if you modify the default settings, .pdf you choose how much compression you want, and a small amount of compression can make a much smaller file size.
    I would recomend using .psd, in cmyk color space. When you make your pdf for printing is when you will decide how much compression and which pdf preset you will use(press ready or PDF X should be a good choice). That will be your important choice.

  • Best way to transfer and delete all project related files?

    I want to work on a project while at school and home.
    1. Is Media Manager the best way to transfer everything I need from one mac to another?
    2. Is there an automated way to delete all of my files from capture scratch, etc. on the school mac when I am done transferring everything to my disk? I would like to make sure no one else can access those files, though I do not want to delete anyone else's work.
    Thanks.

    Go get yourself a big, fast portable firewire drive. Plug it into the school computer. (make sure it is properly formatted first!!!) Navigate to your project's capture scratch folder. Drag the folder to your hard drive. When it's done copying, open as many files as it takes to satisfy you that it has copied successfully.
    Then drag any photos, music, narration etc files to the hard drive. Finally, copy your fcp project file to the hard drive.
    When you're SURE you've got everything successfully, un mount the firewire drive. Then do all the above again, but this time drag the files on the school computer to the trash and empty the trash.
    All this assumes no other twit captured into your folder, but hey what the heck, live and learn.

  • Best way to export as a uncompressed 8 bit file

    I'm trying to import a HD quicktime clip into final cut express. Trim it on both ends and then export it as an Apple uncompressed 8bit 4:2:2 file. What is the best way to do this without creating any artifacting or compression?
    Pretty new to final cut....
    Thx

    Put the video in an HD sequence. Trim the beginning and end. Make sure nothing is rendered. Export to QuickTime conversion, set the codec to none.

  • Best way to transfer Betacam SP tapes to AVI files?

    What would be the most cost effective way to transfer Betacam SP tapes to AVI files?
    I have a Betacam SP deck, Final Cut, and a Mac Pro.
    I just need to connect the Betacam SP deck to the Mac Pro.
    Thank you in advance for any thoughts.

    +" ... I need to convert these tapes into the best possible, broadcast quality file format ... "+
    If you are doing it yourself, DV is about the only way you can go. There are no A-D converters that I know of that save to Apple Intermediate Codec or ProRes (and you would need FCStudio to do ProRes, anyway - are you using FCExpress or FCPro?).
    Canopus does have a (more expensive) HD series converters - the ADVC-HD50 runs about $650 and converts analog to HDV, but that in turn would need to be converted to Apple Intermediate Codec in order to use it in FCExpress.
    +" ... Everyone (PC heads) has been telling me to go AVI. What would you suggest then? ..."+
    Even pc heads should know better than AVI.
    But what is your intended purpose? Burn to DVD, provide to a TV broadcast, put on a website, upload to YouTube? That would really determine the 'best format'.

Maybe you are looking for

  • How to create a form with sequential file numbers everytime it is saved?

    I created a pdf form in LiveCycle and my plan is to have people to fill in the form, then print it. Each time the person fills in the form, it should have a new file number. Like the old carbon copy receipts. I believe that either it counts and verif

  • Illustrator Subscription isn't working

    Purchased a month-to-month subscription to Illustrator which is now not activating because it says I need to connect to the internet. I am clearly connected to the internet and really need to just get some work done and stop wasting my time trying to

  • Error when Calling Session Bean from BPEL .

    Please Help ? Has anyone experienced this before Oracle BPEL Process Manager Full Cycle An unexpected error has occurred while executing your request. This is most likely related to a defect in the Oracle BPEL Process Manager product. We apologize yo

  • Characteristic combinations

    I have to implement the following scenario/ I have product as a characteristic.  But it is actually product category.  There are 8 categories.  Each category has 1 to 10 products.    How do I implement this? Product categories: x1, x2, x3, …, x8 X1 -

  • Incremental aggregation in OWB

    Hi all I have a strange requirement to get an incremental aggregation done and stored in one particular column based on changes to other columns of a dimension. Suppose I have a dimension COUNTRY_DIM as follows COUNTRY_SK COUNTRY_CODE *( BUSINESS KEY