Accessing a file over the network

Hi ,
I need to access a file for read/write operations. The file may exist or may not on another computer in my network. I use the File class for accessing the file. (File f = new File("\\192.23.23.23\file.txt");
My problem is how can I know if I cannot access the file because I have network issues (e.g. The file exists but the network is down so its not accessible) or because the file really dont exist on the given address.
Since File operations does not throw a specific exception Its hard to know the exact reason for access failure.
Any suggestions ?
Thanks.

Javaist wrote:
Hi ,
I need to access a file for read/write operations. The file may exist or may not on another computer in my network. I use the File class for accessing the file. (File f = new File("\\192.23.23.23\file.txt");
My problem is how can I know if I cannot access the file because I have network issues (e.g. The file exists but the network is down so its not accessible) or because the file really dont exist on the given address.
Since File operations does not throw a specific exception Its hard to know the exact reason for access failure.
Any suggestions ?Here's a complete hack that only uses File that is completely coupled to Windows and the "\\hostname\dir\file..." syntax. This is not a universal solution and strongly urge you not to use it:
public class NetworkFileTest {
   public static void main(String[] args) {
      File file = new File("\\\\myhostname\\tmp\\filethatexists");
      if ( file.exists() ) {
         System.out.println("File exists");
      } else {
         if ( hasPathToHost(file) ) {
            System.out.println("File doesn't exist");
         } else {
            System.out.println("No path to host");
   private static boolean hasPathToHost(File file) {
      if ( file.exists() ) {
         return true;
      } else {
         file = file.getParentFile();
         if ( file != null ) {
            return hasPathToHost(file);
         } else {
            return false;
}This just recursively checks the parent to see if it exists. Once it gets up to the host "directory," it will return false if the network is down, or true otherwise.
Remember that there's absolutely no way to check if a remote file exists if the network is down, short of carrier pigeons. This will just tell you if the file might exist.
Edited by: endasil on 9-Oct-2009 10:43 AM

Similar Messages

  • Streaming audio file over the network w JMF. How to know when the file end

    Hi
    I am streaming audio file over the network using JMF. I want to be able to know when a file end so I can close the streaming session.
    Can some one please help
    Thanks

    If you put a ControllerListener on the Processor that's associated with generating the RTP stream, it'll generate an "EndOfMedia" event when the end of the file is reached.

  • Corporate Win7/Office 2010 | Severe Lag when opening Office 2010 files over the network

    Good Evening Everyone,
    I work in a corporate environment for one of the top banks in the country (USA). We recently upgraded our computers to Windows 7. (The image has office 2010 included in the build)
    I've been experiencing some severe lag when opening Office files over the network. Let me start by saying I've researched a lot and have yet to find a solution that works or even makes much of an improvement. 
    Notes: My laptop is new (64-bit Win 7 Enterprise). The remote desktop where the files lie is new as well. (64-bit Win 7 Enterprise) Both computers have good hardware and more than enough juice to handle applications. 
    There are certain files I work on along with other co-workers that we store on a computer within the office. We simply create shortcuts to the files on our local machines and make changes, etc. from there. However, after this upgrade, every time I try to
    open a file on the remote computer, it takes over a 1 minute to load. I've spoken to our support team who sent someone out and confirmed it's not the network. 
    Both computers are on the same subnet as well. I've changed the trust center settings on both the client computers and "server" to trust any computer on the network. I have also changed the network card's speed from "Auto Negotiate" to
    full duplex 100mbps with no luck.
    I am out of options here and in desperate need for a fix. Even saving changes to a file we work on takes forever. 50% of the time when I close a spreadsheet, the title bar has a not responding message and takes a minute to eventually close. 
    PS: Extra Info : All computers run McAfee AV and use McAfee for disk encryption. I've confirmed all computers are up-to-date in every respect with the AV software. 
    Thanks,

    Try: 
    Open My Computer.
    Open the Tools menu and choose Folder Options...
    Select the File Types tab.
    Select the extension (for example DOC, or XLS) of the file that is slow to open.
    In the Details section, click [Advanced], and another dialog box will open. 
    In the Actions section, click Open then click [Edit...], and another dialog box will open.
    http://windowssecrets.com/forums/showthread.php/149672-10-9-2012-Updates-and-very-slow-opening-of-Office-files
    KR

  • WIFI dies when transferring big files over the network

    Hi, I have Dell Inspiron 1520 with ipw3945 driver, when I transfer big files over the network, my wifi dies, anybody knows what could it be? If you need additional information, feel free to ask...
    Thanks in advance

    I guess we shall see. I can't imagine we are the only 7 with these issues.  Mine is mainly just lag... and overall slowness.  I hope to work through this.  If it lasts much longer I will have to revert back all 3 of my lappies to FC which I really do not want to do.  But on the lappies i connect via wireless 90% of the time and need it to work. 
    By the way how are you guys configuring your wifi?  I am using the iwl drivers and wicd.
    Well I did some more testing and loaded up netcfg and still get the same results so that rules out that part.  I also did some packet captures and I am getting a bunch of tcp retransmissions followed by tcp segment lost followed by a reset which in turn kills my rdp session (remote desktop protocol). I also went back several versions of the uucode driver and still get the same reults so I guess it seems to be a kernel issue.  Back to FC I go.  Damn shame...
    Last edited by BKJ (2008-10-08 01:08:56)

  • I need to copy files over the network PSSession . ( Firewall / DMZ / Etc. )

    Hello
    I need to copy files over the network PSSession . ( Firewall / DMZ / Etc. )
    I have a script where I copy from my local server ( server1) to the remote server ( server2 ), but I can´t not make script that will copy from the remote server to my local by my session. From server2 to server1
    Script is as below ...:-)
    HELP : ....
    winrm s winrm/config/client '@{TrustedHosts="SERVER2"}'
        $Source = "D:\test\ok.log"
        $Destination = "D:\test\ok.log"
        $session = New-PSSession -ComputerName SERVER2
    Set-StrictMode -Version Latest
    ## Get the source file, and then get its content
    $sourcePath = (Resolve-Path $source).Path
    $sourceBytes = [IO.File]::ReadAllBytes($sourcePath)
    $streamChunks = @()
    ## Now break it into chunks to stream
    Write-Progress -Activity "Sending $Source" -Status "Preparing file"
    $streamSize = 1MB
    for($position = 0; $position -lt $sourceBytes.Length;
        $position += $streamSize)
        $remaining = $sourceBytes.Length - $position
        $remaining = [Math]::Min($remaining, $streamSize)
        $nextChunk = New-Object byte[] $remaining
        [Array]::Copy($sourcebytes, $position, $nextChunk, 0, $remaining)
        $streamChunks += ,$nextChunk
    $remoteScript = {
        param($destination, $length)
        ## Convert the destination path to a full filesytem path (to support
        ## relative paths)
        $Destination = $executionContext.SessionState.`
            Path.GetUnresolvedProviderPathFromPSPath($Destination)
        ## Create a new array to hold the file content
        $destBytes = New-Object byte[] $length
        $position = 0
        ## Go through the input, and fill in the new array of file content
        foreach($chunk in $input)
            Write-Progress -Activity "Writing $Destination" `
                -Status "Sending file" `
                -PercentComplete ($position / $length * 100)
            [GC]::Collect()
            [Array]::Copy($chunk, 0, $destBytes, $position, $chunk.Length)
            $position += $chunk.Length
        ## Write the content to the new file
        [IO.File]::WriteAllBytes($destination, $destBytes)
        ## Show the result
        Get-Item $destination
        [GC]::Collect()
    ## Stream the chunks into the remote script
    $streamChunks | Invoke-Command -Session $session $remoteScript `
        -ArgumentList $destination,$sourceBytes.Length
        Remove-PSSession -Session $session

    But have will the script look,  if i need to copy from
    From server2 to server1.
    My script copy from server1 to server2 and working, but I need server2
    to server1.

  • Weird X on corner of copied file over the network

    i was copying a file from my Mac Pro (Lion) to my MBP (ML) over the network and i noticed this little x in a black box on the top left hand corner of the icon while it was being copied.
    does anyone know if this is normal?
    the two little red marks mean that the file is a windows file for my virtual machine but i have seen this x before and i was curious to know if this is in fact a Mac OS functionality.
    TIA

    OK. weird. the files on my dropbox have this weird blue x and then a green checkmark in this spot if i am not mistaken.
    so we are saying this is a function of a PROGRESS BAR and it goes away when the copy has completed?
    i mean, it did go away over here but i don't remember seeing it before for some reason.
    THANKS

  • I cannot printany web pages or emails over a wireless home network. My OS is windows 7 and am using an Epson printer. I know I have the home network set up correctly as i can print files over the network.

    I cannot print any email or web pages over a wireless home network. I know that I can print my files over this network, just not anything from the web or emails using Firefox. I am using Windows 7 and printing to an Epson.
    == This happened ==
    Every time Firefox opened
    == when I set up the wireless home network.

    The most likely reason for this is that the wrong printer is chosen in the File->Print window.
    In Firefox, go to File->Print and click the dropdown box with printer names. Ensure that the correct network printer is selected, then try printing again.

  • Bluetooth mouse cuts out when transferring files over the network

    Just as the title says: whenever I copy files to a PC over the network (via SMB I think its called) My bluetooth mighty mouse will start getting very jerky and makes is very difficult to move the cursor on the screen. However, my Bluetooth keyboard is comply fine. Both are using Lithium batteries and where just replaced about a month ago. Also, both are in close range...about 2 feet. And it only happens when coping files.
    Any ideas?
    -Scott

    I don't connect to network volumes that often, but I did again today and noticed that my bluetooth keyboard completely cut out (had the "discounted" HUD come up) and then the keyboard would not reconnect until the file copy was complete. I don't know about the mouse as lately I've been using my Microsoft mouse that hasn't been giving me any troubles. (like really, Microsoft and "no troubles" in the same sentence??? lol)

  • Slow access when opening XLS or DOC files over the network but XLSX and DOCX files are fast

    I am working with a small office that has 3 Windows 7 Pro PC's.  Two of these PC's have shared folders that hold Word and Excel files and all 3 of the PC's have drives mapped to these shared folders.  When browsing these mapped drive in Windows
    Explorer  and double-clicking a file 1 of the computers takes about 30-50 seconds to open any file with a .doc or .xls extension.  It opens .docx and .xlsx files in a couple seconds though, it also open PDF files very quickly.  The other 2 PC's
    have no trouble any any type of file.  I have tried many things over the last couple weeks to get this fixed.  I have added the file locations as 'trusted locations' in the Trust Center and added a couple Registry tweaks to the SMB/ lanman workstation
    and server. 2 PC's are running Office Pro 2010 SP2 and the other is Office Pro 2013, the one having the slow access is running Office 2010.  Has anyone come across this problem and have any advice??

    Try: 
    Open My Computer.
    Open the Tools menu and choose Folder Options...
    Select the File Types tab.
    Select the extension (for example DOC, or XLS) of the file that is slow to open.
    In the Details section, click [Advanced], and another dialog box will open. 
    In the Actions section, click Open then click [Edit...], and another dialog box will open.
    http://windowssecrets.com/forums/showthread.php/149672-10-9-2012-Updates-and-very-slow-opening-of-Office-files
    KR

  • How to access a file in the network shared drive

    Hi,
    I have a pdf file in a netwoek share drive which opeates on windows platform. I want to access this file. the path to the file looks something like this
    acddfd\sap\sapdir\myfile.pdf
    I have tried gui_upload , gui_download , ws_upload and ws_download FM. But I am getting file_read error. Is therey any settings i need to made.
    I can access the above path from windows menu start->run.
    points guarnateed.
    Thanks
    sankar

    GUI_UPLOAD / DOWNLOAD is the way to go. If you can access the directory/file that doesn't mean necessarily that the R/3 system can 'see' it as well. Your local frontend is connected to that share, but I would check with your basis that the application servers where R/3 is running do have access to that share as well.
    Also does the R/3 user you are using have the same access right to the network as your Windows Network user?
    We had a similar problem and eventually it was just an authorization issue with the R/3 user.
    Hope that helps,
    Michael

  • Sharing and Accessing Folders & Files over a Network

    Structure:  2 iMac desktops linked together over an ethernet connection.  NO SERVER.
    I'm having trouble getting folders shared on my new iMac.  I'm an ex-windows guy, and in Windows you only have to share a main folder or sub folder to get access to the files.  I have two folders shared between 2 different iMacs, but I can't access the files there, as I get a "you don't have permission" warning.
    I get conflicting information when I share folders then "add" people to the permissions list.  It shows me as kevsahl, but when i go to add myself to my office managers machine, it shows me as my contact in the address book.  Why is it so difficult?
    Everything about the MAC is easier, to me any way, so can someone please tell me the secret shortcut to making this an easy task!
    Thanks!
    Kevin
    (2) iMac
    (1) Macbook Pro 13"
    (1) iPad2
    (4) iPhones

    I apologize, it appears I'm in the wrong forum.  you are correct, i don't have a PPC, just the basic new iMac with Snow Leopard.
    Sorry!  I'll post this in the appropriate area.
    Kevin

  • Trouble sending files over the network.

    I have a network application that corrupts any files that it sends, although the received file is very close (but never exact) to the number of bytes it should be. There is a socket client that each client has, and the Packet data structure is searializable and simply contains a string message and the byte[]. Am I doing something wrong?
    Here is my code for Sending:
    ObjectOutputStream toOtherClient = new ObjectOutputStream(client.getOutputStream());
    ObjectInputStream fromOtherClient = new ObjectInputStream(client.getInputStream());
    Packet fileRequest = (Packet)fromOtherClient.readObject();
    File file = new File(DefaultConfig.defaultFileDirectory+"\\"+fileRequest.getMessage());
    FileInputStream fromDisk = new FileInputStream(file);
    BufferedInputStream fromDiskBuffered = new BufferedInputStream(fromDisk);
    byte[] buffer = new byte[maxPayload];
    while(fromDiskBuffered.available() > 0)
         if (fromDisk.available() > maxPayload)
              fromDiskBuffered.read(buffer);
              toOtherClient.writeObject(new Packet(Packet.Command.File,"",buffer));
         else
              buffer = new byte[fromDiskBuffered.available()];
              fromDiskBuffered.read(buffer);
              toOtherClient.writeObject(new Packet(Packet.Command.File,"",buffer));
    fromDiskBuffered.close();
    fromDisk.close();
    toOtherClient.writeObject(new Packet(Packet.Command.File,"ack"));
    fromOtherClient.close();
    toOtherClient.close();
    client.close();Here is my code for recieving:
    Socket client = new Socket(host, Integer.parseInt(port));
    ObjectOutputStream toOtherClient = new ObjectOutputStream(client.getOutputStream());
    ObjectInputStream fromOtherClient = new ObjectInputStream(client.getInputStream());
    FileOutputStream toDisk = new FileOutputStream(DefaultConfig.defaultFileDirectory+"//"+whatFile); BufferedOutputStream toDiskBuffered = new BufferedOutputStream(toDisk);
    toOtherClient.writeObject(new Packet(Packet.Command.File,whatFile));
    Packet incoming;
    while(true)
         incoming = (Packet)fromOtherClient.readObject();
         if (incoming.getMessage().equals("ack"))
              break;
         byte[] fileData = (byte[])incoming.getData();
         toDiskBuffered.write(fileData);
    toDiskBuffered.flush();
    toDiskBuffered.close();
    toDisk.close();
    fromOtherClient.close();
    toOtherClient.close();
    client.close();

    You're assuming that available() gives you the total length of the file, which it doesn't, and you're ignoring the result returned by the read call, so you're assuming you've read data you may not have read.
    I would rethink the tactic of reading the entire file into a single buffer - this doesn't scale. It's only safe if you know that the file size has an upper bound and that this is relatively low.

  • Parsing file over the network

    We are using Xerces implementation of jaxp - (xercesImpl.jar, xmlParserAPIs.jar).
    Below is my code:
    DocumentBuilder builder = getBuilder();
    java.io.FileInputStream fi = new java.io.FileInputStream(�file://c$/config/tmp.xml�);
         org.w3c.dom.Document outNode = builder.parse(fi);
         fi.close();
    Inside the tmp.xml is reference to tmp.dtd without specifying any path, just tmp.dtd. The line of code that parses the file throws exception that it can�t find tmp.dtd and it shows me the path where it expects it to be � it is a current user directory. Is there a way of telling the implementation to look somewhere else for files referenced by the file being parsed?.
    Janusz

    yes, intercept the calls to the DTD and point the parser to the right file:
    builder.setEntityResolver(new EntityResolver() {
      public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId)
             throws SAXException, java.io.IOException
        if (systemId.endsWith(".dtd"))
          return new InputSource(new FileInputStream("mypath/"+systemId));
        else return null;

  • Sharing Files over a network!

    I'm on a network with many other users, some of which are PC's and was wondering how I could share some of my files over the network. How would I go about making a folder or group of folders which are able to be accessed (either with or without a password) on the network. Making sure that only the files within the specified folders is placed on the network?
    Any help would be much appreciated!
    Thanks!

    Checkout SharePoints.

  • Cannot Copy Files over a network

    I've had a new hard drive installed in iMac by Apple, and Apple re-installed the OS, which is running 10.6.7 (all current software updates are installed). The iMac is part of a network connecting to a OS X Server 10.4.10
    All of the Network Drives have been connected, the user can copy documents under 1MB to and from the server fine. However if we try to copy files over 1MB the first file will copy fine, but then no more files can be copied to the server from this machine, regardless of the size.
    If i use another Mac, with the same user credentials I can copy files of any size without any issues. I have tried connecting to the Network using both the Ethernet port and Airport but I experience the same issue regardless.
    If I reboot the iMac I can copy a file over 1MB again and then the symptoms re-present themselves. I have tried creating a users, new network drives, folders etc. I can connect using any user, to any of the new folders from any other machine on the network but not from this one.
    When the copying fails Finder just hangs with
    Copying "" to "ShareName" rather than having the name of the file, I believe this may be where the error lies.
    I have also tried running the App Maintenance from Titanium Software, after running this i can copy files over the network fine, but after I have copied 10 or so files, the situation goes back to not copying files correctly. 
    Tags:

    I have tried several files and also I have copied the files on to a USB Hard Drive and then onto another machine, that machine was able to copy the files over the network.
    The Firewall is switched off on this Mac, I have tried various different options with the Firewall, Turning it off, ensuring the AFP connections are allowed.
    Also using the Maintenance app, that I mentioned clears the Caches, repairs permissions etc etc

Maybe you are looking for

  • How do I make Vertical Spry Menu appear in IE

    The URL in question is: http://www.ambppct.org/index_menu.php I have inserted a Vertcal Spry Menu on this page. It functions perfectly in Safari, Firefox and IE 8. However it does not appear in previous versions of IE. Below is the css file: @charset

  • Unexpected loop behaviour with asynchronous call

    I am having trouble with loop behaviour when using an asynchronous call. I am building an application to record simultaneously temperature (NI USB-TC01 thermocouple), displacement (DC voltage, read from an Agilent 34401a) and resistivity (using a Kei

  • Create a loop with Caustics?

    I'm looking to create a looping underwater effect using the Caustics generator, although I am not entirely sure how to do it. I've played around with the timing etc... but I would like to think that there is a better way to accomplish this.

  • Error 1603 Voice Over Kit

    I can´t install Voice Over Kit in my fith iPod nano. The computer said error unknow (1603). What I can do? Message was edited by: Fco Javier

  • Selecting type on a flipped path

    There seems to be no way to select individual characters in order to kern type on a path when the text has been flipped. I often create type on a circle that I flip, but can find no way to edit individual characters. Anyone have any ideas? Thanks so