How to replace or remove last 500 bytes of a file without rewriting all the file?

Hi everyone,
Usually I only ask for help when I can't find a solution for several days or weeks... And guess what? That just happen!
So, this is what i am trying to do:
I have a program to ZIP folder and protect them with password, then it encrypts the zip file.
That it's working fine, until the user forgets his password.
So, what I want to do is give the user a Recovery Password option for each ZIP file created. I can't use the Windows Registry because the idea is to be able to recover the password in any computer.So i came up with an idea...
In simple terms, this will work like this:
0 - Choose folder to ZIP
1 - Ask user for recover details (date of birth, email etc)
2 - ZIP folder with password
3 - Encrypt ZIP file
4 - Encrypt recover details and convert it to HEX
5 - Add recover details (in HEX) to the end of the ZIP file (last bytes)
6 - Add "5265636F76657244657461696C73" which is the text "RecoverDetails" in HEX
7 - Add "504B0506000000000000000000000000000000000000" this is the final bytes of a ZIP file and will make the Operating System think that is a ZIP file (i know that will give an error when we try to open it.. the ideia is to change the
extension later and use my software to do all the work to access this ZIP/folder again)
So, explaining what it's here, I want to say that I managed how to do all of this so far. The point number 6 will help us to determine where the recover details are in the file, or if they actually exist because user can choose not to use them.
In order to unlock this ZIP and extract it's contents, I need to reverse what I've done. That means, that  need to read only the last 500 bytes (or less if the file is smaller) of the ZIP and remove those extra bytes I added so the program can check
if the user is inputing a correct password, and if so decrypt contents and extract them.
But, if the user insert a wrong password I need to re-add those bytes with the recover details again to the ZIP file.
The second thing is, if the user forgets his password and asks to recover it, a form will be shown asking to insert the recover detail (date of birth, email etc), so we need to reed the last 500 bytes of the ZIP, find the bytes in number 6 and remove the
bytes before number 6, remove bytes in number 6 and number 7, and we will have the recover details to match against the user details input.
I have all done so far with the locking process. But i need help with the unlocking.
I am not sure if it's possible, but this what i am looking for:
Read last 500 bytes of a file, remove the bytes with recover details and save the file. Without reading the whole file, because if we have a 1GB file that will take a very long time. Also, i don't want to "waste" hard drive space creating a new
clone file with 1GB and then delete the original.
And then add them back "in case user fails the password" which should be exactly the same.
This sounds a bit confusing I know, even to me, I am writing and trying to explain this the better I can.. Also my English is not the best..
Here it goes some code to better understanding:
'READ LAST 500 BYTES OF ZIP FILE TO CHECK IF IT CONTAINS RECOVER DETAILS
Dim oFileStream As New FileStream(TextBox_ZIP_to_Protect.Text & ".zip", FileMode.Open, FileAccess.Read)
Dim oBinaryReader As New BinaryReader(oFileStream)
Dim lBytes As Long = oFileStream.Length
oBinaryReader.BaseStream.Position = lBytes - 500
Dim fileData As Byte() = oBinaryReader.ReadBytes(500)
oBinaryReader.Close()
oFileStream.Close()
Dim txtTemp As New System.Text.StringBuilder()
For Each myByte As Byte In fileData
txtTemp.Append(myByte.ToString("X2"))
Next
Dim RecoveryDetailsPass_Holder = txtTemp.ToString()
'Dim Temp_2 = txtTemp.ToString()
'RichTextBox1.Text = txtTemp.ToString()
If txtTemp.ToString.Contains("505245434F47414653") Then
'we have password recovery details(the numbers mean RecoverDetails in HEX)
'next we will get rid of everything before and after of string "cut_at"
Dim mystr As String = RecoveryDetailsPass_Holder 'RichTextBox1.Text
Dim cut_at As String = "505245434F47414653"
Dim x As Integer = InStr(mystr, cut_at)
' Dim string_before As String = mystr.Substring(0, x - 1)
Dim string_after As String = mystr.Substring(x + cut_at.Length - 1)
RecoveryDetailsPass_Holder = RecoveryDetailsPass_Holder.Replace(string_after.ToString, "")
RecoveryDetailsPass_Holder = RecoveryDetailsPass_Holder.Replace("505245434F47414653", "") ' this is RecoverDetails in HEX
RecoveryDetailsPass_Holder = RecoveryDetailsPass_Holder.Replace("504B0506000000000000000000000000000000000000", "") ' this is the bytes of an empty zip file
'AT THIS POINT WE HAVE ONLY THE RECOVER PASSWORD DETAILS (date of birth, email etc) IN THE VARIABLE "RecoveryDetailsPass_Holder"
'////////////////////////////////////////////////////// TO DEBUG
'MsgBox(string_after.ToString & "505245434F47414653")
'InputBox("", "", string_after.ToString)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ TO DEBUG
'Temp_2 = Temp_2.Replace(RecoveryDetailsPass_Holder.ToString, "")
Now that we have the recover details, we need to remove them from ZIP in order to the software try to unzip it with the password provided by the user on the GUI.
If the user needs to recover the password we have the details already in RecoveryDetailsPass_Holder variable and just need to match them against user input details.
If the user fails, we need to put the RecoveryDetailsPass_Holder back on the file.
Any question just ask, it's a bit trick to explain i think, but please ask.
Anyone know how to do this?
Many thanks in advanced.
Nothing is impossible!
@ Portugal
Vote if it's helpfull :)

@ ALL
Thank you very much for you help. I know that if I'm "playing" with bytes you should assume that I know a lot of VB.net, but I don't know that much unfortunately. I am not a beginner but I am still very fresh and I probably do stuff that work but
probably not in the best way...
Anyway, I will explain the idea of this little software I'm making. Once I wanted to create a program to protect folders with password, and I came up with something to change folder permissions to lock access to them, and that actually worked fine and quickly.
However, I managed how to "crack" the protection by going to folder properties, security tab and then give permissions back to my username. So that, to me, wasn't a safer system to protect folders, also I want the ability to use passwords. So I search
and search online for a way to do it, and someone replied (to someone with the same question as me) that the best option would be to create a zip with all contents of the folder, with password and then change the extension from .zip to .whatever and register
the new extension .whatever on the Windows Registry, so that file will have an icon and open with my software.
So I did...The program zips everything, change the extension and I added the encryption to avoid people changing the extension to ZIP or trying to open with 7-Zip or similar and be able to see the protected files names in the .zip/.whatever
Answering to all of you now:
@Armi
"System.IO.FileStream.SetLength"
I know I tried that but I erased the code because it didn't work for some reason, I don't remember why sorry, was long time before I created this post.
The last code I was trying to use was this:
' Set the stream position to the desired location of the stream.
Dim fileStream As IO.FileStream = _
New IO.FileStream(TextBox_ZIP_to_Protect.Text & ".zip", IO.FileMode.Append)
Try
' Set the stream (OFFSET) position to the desired location of the stream.
fileStream.Seek(210, IO.SeekOrigin.Current)
Dim Bytes_do_ZE As Byte() = HexStringToByteArray(Temp_2.ToString)
'Write Characters ASCII
For Each Byte_Do_Zeca As Byte In Bytes_do_ZE
fileStream.WriteByte(Byte_Do_Zeca)
Next
Finally
fileStream.Close()
End Try
and we need this:
Private Shared Function HexStringToByteArray(ByRef strInput As String) As Byte()
Dim length As Integer
Dim bOutput As Byte()
Dim c(1) As Integer
length = strInput.Length / 2
ReDim bOutput(length - 1)
For i As Integer = 0 To (length - 1)
For j As Integer = 0 To 1
c(j) = Asc(strInput.Chars(i * 2 + j))
If ((c(j) >= Asc("0")) And (c(j) <= Asc("9"))) Then
c(j) = c(j) - Asc("0")
ElseIf ((c(j) >= Asc("A")) And (c(j) <= Asc("F"))) Then
c(j) = c(j) - Asc("A") + &HA
ElseIf ((c(j) >= Asc("a")) And (c(j) <= Asc("f"))) Then
c(j) = c(j) - Asc("a") + &HA
End If
Next j
bOutput(i) = (c(0) * &H10 + c(1))
Next i
Return (bOutput)
End Function
That code, as I understand, is to search for the OFFSET of the bytes in the file and start to write from there... That OFFSET should be the beginning of the 500 bytes read on the code before. I got the OFFSET position "210" reading the file with
the HEX editor "HxD - Hexeditor v1.7.7.0" but using the OFFSET won't work because every file, password, recover details and so on, are different and so the file size, changing the OFFSET I
think.
@Reed Kimble
Does that sound like something which might work for you?
Thanks for your help. That might be some solution, however it seams a bit of the same problem where we need to read the bytes again to get the recover details. But, as I said in this post, because this is meant to password protect folders, do you think that
will apply as well?
@Crazypennie
Thanks for your reply.
All this appears really weak. The user has your application since he need it to open the file .... and the code in the application contain the code to read the file without knowing the password. Therefore anyone can read your code and retrieve the
data without the password ... if he knows VB.
The application can only open the file if the user didn't use a password to protect the file. Because the file is encrypted and needs to be unencrypted first.
When the application tries to open/read the file, will need to decrypt it first and then check for a password and do the validation. Also the application is with the code masked/protected which i think it might not be easy for reverse engineering.
- You need to use a web server and a symmetric key encryption
This a good idea, besides I don't know how to implement it. However the idea is to be able to:
1 - Protect a folder anywhere in any Windows computer (portable app)
2 - Recover password details (security question) in any computer, online and offline
And I think we need a computer always connected to the Internet to use that method, right?
@ Mr. Monkeyboy
Thank you very much for your effort.
I just wanted to let you know that the zip method you are using is no longer supported.
I didn't actually knew that. Thanks for letting me know.
Do you require the compressed encrypted files to actually be Zip files or could they just be compressed files that have nothing to do with Zip?
No, it doesn't need to be a .zip extension. I am actually using my own extension. It starts as a Zip but then I changed to my own extension which I have registered on the Windows Registry.
@ ALL
Thanks again to all for trying and spending time helping me.
By the way, I might not be able to answer or try any code during the weekend... It's easter break and family is around. Have a nice easter everyone. :)
Nothing is impossible! Imagination is the limit!

Similar Messages

  • HT4847 I changed my iPhone from an IPhone 4 to an iPhone 5. How do I delete my iCloud account on my old phone without losing all the data on my new iPhone 5?

    I changed my iPhone from an IPhone 4 to an iPhone 5. How do I delete my iCloud account on my old phone without losing all the data on my new iPhone 5?

    If you have any photo stream photos on your old phone that you want to keep you might want to save them to the camera roll, then import them to your computer (http://support.apple.com/kb/HT4083) before deleting the account.  The reason for this is that photo stream photos are only kept in iCloud for 30 days.  When you enable photo stream on your new phone you will only receive photo stream photos from the last 30 days as older photos are no longer in iCloud.

  • How do I deal with a fire wire HD after iSight has corrupted all the files?

    Hi
    When I bought iSight I was unaware that it works with pityfully few firewire hubs such as Belkin powered FW hub. I corrupted two drives before asking the forum who were very helpful.
    After the corruption the files could not be read from the HD nor could the HD be written to. I managed to get the data off the HDs by connecting to another computer. They work perfectly on the other rig. However when I try to use them on the computer that they were corrupted on it is the same no IO without an error message. I have tried all the usual privileges stuff, ignore ownership etc but no go. Any ideas as to how I can use them with the original computer?
    Thanks all
    Gordon
    Intel Mini Duo   Mac OS X (10.4.6)  

    Hello Again Gordon Bennet!,
    The above was the easy fix for your problem which is an I/O issue.
    If you want to live on the edge, AFTER making a backup, are you are familiar with with how to use 'Console'? It's in Applications-Utilties-Console.
    If so, can you access the logs and see if the sort of read error that has been logged? It is also possible (although improbable) that the OS logged a detailed message elsewhere.
    Good luck and even though not "solved" here in the iSight group, you might try your HD question in Computing Hardware and under your MacMini group to see if anyone has better answer/solution.
    Respectfully,
    Bill Gallagher

  • How can I open a PDF file without first saving the file?

    How can I open a PDF file without first having to save the file?

    How can I open a PDF file without first having to save the file?

  • How do I sync my iPad with a new iTunes library without erasing all the previously purchased apps & data on my iPad?

    I'm sure this is a common issue, and I've google-searched for solutions but I cannot find a straight forward answer anywhere. I really hope an expert here can help me out.
    I purchased an iPad last year and synced it with my iTunes library on my old PC laptop. Well, my PC laptop harddrive crashed last week and I cannot access anything on my laptop anymore. I did not make a back-up for my PC harddrive either. I know, next time I should make a back-up and I will. But that's irrelevant. The PC is gone now.
    I replaced my PC this week with a brand new Mac Book Pro. Excited about my new purchase, I quickly hooked up my iPad with the hopes of easily transferring and accessing my iPages, iNumbers, and other productivity iPad apps seamlessly to my new beautiful Mac Book Pro. But now I've run into the nightmarish dilemma of not being able to sync my beloved Ipad with my new MAC without getting the warning that basically says "your iPad is already synced with another iTunes Library. You may only sync to one iTunes Library at a time. You will lose all your data if you sync to this new computer."
    Can someone give me a straightfoward answer as to how I can sync my iPad with my new iTunes Library on my new Mac Book Pro without losing any of the apps that I previously purchased? I want to be able to access the apps I downloaded on my iPad on my Mac Book Pro.
    Thanks so much!!!!!!

    how to use iTunes to sync is in the
    http://www.apple.com/support/itunes
    For MacBook Pro community and OS X
    MacBook Pro
    https://discussions.apple.com/community/notebooks/macbook_pro 
    https://discussions.apple.com/community/mac_os?view=discussions
    http://www.apple.com/support/macbookpro
    While it isn't as easy to just use a Mac iDevice as media storage as Android and Windows, you can add documents and such like Word, PDF and others manually in iTunes to have them sync as well.
    http://support.apple.com/kb/HT1386
    http://support.apple.com/kb/HT1351
    They are all there searchable from Bing, Google or every Mac product has a support page.
    http://www.apple.com/support/

  • My computer was stolen. How do I sync my ipod touch with my new computer without wiping all the music

    My laptop was stolen and now when I try to sync my music it wants to wipe my ipod touch 5th generation. How do I get around this ?

    There are quite a few third party apps that will copy media from the ipod to the computer. Try searching the cnet downloads site or other reputable sites.
    Good luck!

  • My ipod shuffle is connected to another library that is no longer in use. How can I connect it to my library on my computer without erasing all the songs it presently has?

    My son downloaded songs onto my ipod shuffle from his friend's computer but I have no access to that computer. When I try to connect to my library from my computer I get a message saying that in order to sync w/my library I have to erase all content. Is there any other way to connect this shuffle w/out erasing all these songs?

    HELPPP ME BEFORE CHRISTMASS MORNING!!

  • How can I use a word file without pages changing the file

    I want to edit this word file I created, but pages either can't open it because i sent it via email from google docs, or it will change it completley. I don't want to get Office for mac, so What Do I Do?

    http://www.libreoffice.org
    It's open-source and quite nice and full-featured

  • How to transfer file from ipod touch to i tunes. i have files in my ipod , ut itunes is  new so its telling if u sync the ipod all the files will be replaced but no files in the itunes.. so kindly help me how to transfer the files  from i pod to itunesb

    how to transfer file from ipod touch to i tunes. i have files in my ipod , ut itunes is  new so its telling if u sync the ipod all the files will be replaced but no files in the itunes.. so kindly help me how to transfer the files  from i pod to itunes......

    Some of the information below has subsequently appeared in a document by turingtest2: Recovering your iTunes library from your iPod or iOS device - https://discussions.apple.com/docs/DOC-3991
    Your i-device was not designed for unique storage of your media. It is not a backup device and media transfer was designed for you maintaining a master copy of your media on a computer which is itself properly backed up against loss. Syncing is one way, computer to device, updating the device content to the content on the computer, not updating or restoring content on a computer. The exception is iTunes Store purchased content.
    iTunes Store: Transferring purchases from your iOS device or iPod to a computer - http://support.apple.com/kb/HT1848 - only media purchased from iTunes Store
    For transferring other items from an i-device to a computer you will have to use third party commercial software. Examples (check the web for others; this is not an exhaustive listing, nor do I have any idea if they are any good):
    - Senuti - http://www.fadingred.com/senuti/
    - Phoneview - http://www.ecamm.com/mac/phoneview/
    - MusicRescue - http://www.kennettnet.co.uk/products/musicrescue/
    - Sharepod (free) - http://download.cnet.com/SharePod/3000-2141_4-10794489.html?tag=mncol;2 - Windows
    - Snowfox/iMedia - http://www.mac-videoconverter.com/imedia-transfer-mac.html - Mac & PC
    - iexplorer (free) - http://www.macroplant.com/iexplorer/ - Mac&PC
    - Yamipod (free) - http://www.yamipod.com/main/modules/downloads/ - PC, Linux, Mac [Still updated for use on newer devices? No edits to site since 2010.]
    - 2010 Post by Zevoneer: iPod media recovery options - https://discussions.apple.com/message/11624224 - this is an older post and many of the links are also for old posts, so bear this in mind when reading them.
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive - https://discussions.apple.com/docs/DOC-3141 - dates from 2008 and some outdated information now.
    Copying Content from your iPod to your Computer - The Definitive Guide - http://www.ilounge.com/index.php/articles/comments/copying-music-from-ipod-to-co mputer/ - Information about use in disk mode pertains only to older model iPods.
    Get Your Music Off of Your iPod - http://howto.wired.com/wiki/Get_Your_Music_Off_of_Your_iPod - I am not sure but this may only work with some models and not newer Touch, iPhone, or iPad.
    Additional information here https://discussions.apple.com/message/18324797

  • When you scroll to the bottom of the list of files in Finder, the left to right scrollbar doesn't let you click the last file and it covers the file for a while until it disappears. Is this a bug? How do I not make that happen?

    When you scroll to the bottom of the list of files in Finder, the left to right scrollbar doesn't let you click the last file and it covers the file for a while until it disappears. Is this a bug? How do I not make that happen?

    An odd workaround: click "Always" in System Preferences/General/Show scroll bars. The scroll bars will always show, but they won't cover your last file.
    See this other post: https://discussions.apple.com/message/20572471#20572471

  • I have a used mac computer. I want to sync and update my iphone. Currently itunes tells me that my iphone is connected to a different itunes account. How do I make itunes sync and update my phone without deleting all the current information on my phone?

    I have a used mac computer. I want to sync and update my iphone. Currently itunes tells me that my iphone is connected to a different itunes account and will sync, but delete everything from my phone. How do I make itunes sync and update my phone without deleting all the current information on my phone?

    Iphone will sync with one and only one cpomptuer at a time.  Syncing to another will erase the current content and replace with content from the new computer.  This is the design of the  iphone.
    It will erase the content when you sync.
    Why not update from the comptuer with which you normally sync?

  • Yours sincerely! I just bought a Sony DCR-SD1000 camera only when installing the cd drivers not supported by the operating system Machintosh. I've contacted the seller said the store did not provide for the apple os. How can I move all the files on the ca

    Yours sincerely! I just bought a Sony DCR-SD1000 camera only when installing the cd drivers not supported by the operating system Machintosh. I've contacted the seller said the store did not provide for the apple os. How can I move all the files on the camera the port out is to use a USB data cable to a laptop for my macbookpro can not read the contents of the file and the camera. I also want to use the lens on the camera as a substitute for the embedded camera on my macbookpro, what should I do to replace the embedded camera on macbookpro with sony camera so that the camera could be more variety and can I record when I turned macbookpro . Please help for this so that I can quickly capture the results from sony camera to my macbookpro. Thank you.

    See this page http://macosx.com/forums/networking-compatibility/296947-sony-camcorder-my-mac.h tml - might be some helpful tips there.
    Clinton

  • My old computer crashed and i just purchased a new laptop. How do i get my library on my new computer without erasing all the songs on my ipod?

    ?

    damfam9 wrote:
    My old computer crashed and i just purchased a new laptop. How do i get my library on my new computer without erasing all the songs on my ipod?
    If ALL your music is on the iPod and it's ALL iTunes purchased content, you log into iTunes with your account on th enew machine and reverse sycn the music back.
    If the music is from cd's and other sources (not iTunes files) then ask over at iLounge what third party solution currently works. (can't recommond it here)
    I have some HUGE instructions here how to get your music off the old comptuer too:
    Recovery options:
    A: If Windows isn't booting:
    You need to boot the computer from a "recovery disk or USB" that has a operating system on it and a graphical user interface to transfer files from your boot drive to a external drive.
    I suggest using the Easy USB Installer to install Ubuntu 10.10 onto a 2-4 GB USB key.
    http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/
    or
    burn a ISO of Ubuntu 10.10 or PartedMagic to a cd-r with ImgBurn or Win 7 right click and burn
    You can use Disk Utility in OS X to select the ISO and burn to cd/dvd as well.
    Once you have it installed, consult this page for your BIOS boot key to hold to get into the BIOS.
    http://pcsupport.about.com/od/fixtheproblem/a/biosaccess_pc.htm
    Plug the USB into the back (if possible) of the computer, connect the external drive and enter the BIOS, set the USB (or CD) as first boot and SAVE.
    Boot off the USB/CD and "Try Ubuntu/Run from disk" DON'T INSTALL. (Parted Magic loads into RAM and ejects CD)
    Once in, go under the menu Places > Computer and transfer your files to the external drive just like you would in Windows, drag and drop.
    (If using Parted Magic double click on the Mount Drive left icon twice, use the two GUI windows to transfer files to external drive, unmount drives, log out/quit in the lower left corner menu option)
    B: If the computer hardware isn't working, but the drive might still work:
    You'll have to remove the power cord and manually extract the hard drive. This might result in some damage.
    There is a powered IDE/SATA to USB adapter for sale online for $20 that you can take that internal hard drive and use it like a external drive to access your files from another Windows machine.
    C: If your iTunes content is deleted...
    It might be recoverable if it hasn't been overwritten yet by fresh data. Undelete software works by reading the 1's and 0's of the files themselves, not what the OS says.
    You need to use undelete software pre-installed before the iTunes content was deleted, or while on a bootable cd/USB and a external drive to transfer the recovered files.
    You can also install undelete type software on a new machine and USE STEP B above to "undelete" the files and recover them directly to the new computer.
    You can't install undelete software or recover files to the same drive your attempting to recover from or it overwrites the deleted data.
    D: If the hard drive doesn't work and...
    The data isn't worth spending $2000-$3000 in a ATTEMPT at platter dissection recovery, then your finished
    If the data on the drive was encrypted, data recovery efforts may be futile, unless it's a encypted file and you transfer it successfuly and have the password to de-crypt it.
    E: If you have a "iDevice" with any content
    It can be synced back into iTunes, check at iLounge what third party software works reliably now and for your version.
    (Once you log into your iTunes account, you can sync ONLY iTunes purchased content back from a iDevice)
    Third party software can recover just about all the items on a iDevice, regardless of it's origin. (can't recommend such software here)
    F: If any of the above is too hard, or the data is of "critical importance"
    Then seek professional computer or forensic level recovery services.
    Get help from someone who has done this sort of thing repeatly and can almost guaranty 100% results.
    There is Linux software that can "rip" all data off a iOS device if that level of attention is needed, seek a professional service.
    Hope this helps in your data recovery efforts.
    Please, backup your data, it's the only thing us IT professionals can't recover.

  • When accessing my itunes library of music I get the notation on all songs ...The song could not be located because the origional file could not be found...how can this be corrected or did Apple wipe out all the files

    wien I access Itunes I get the notification....the song could not be located because the origional filoe could not be found...I have over 2000
    songs in my library ....Does this mean they are all gone....How can one retrieve them???

    This missing song thing happens if the file is no longer where iTunes expects to find it. Possible causes are that you or some third party tool has moved, renamed or deleted the file, or that the drive it lives on has had a change of drive letter. It is also possible that iTunes has changed from expecting the files to be in the pre-iTunes 9 layout to post-iTunes 9 layout,or vice-versa, and so is looking in slightly the wrong place.
    Select a track with an exclamation mark, use Ctrl-I to get info, then cancel when asked to try to locate the track. Look on the summary tab for the location that iTunes thinks the file should be. Now take a look around your hard drive(s). Hopefully you can locate the track in question. If a section of your library has simply been moved, or a drive letter has changed, it should be possible to reverse the actions.
    Alternatively, as long as you can find a location holding the missing files, then you should be able to use my FindTracks script to reconnect them to iTunes .
    Once you've sorted out the broken links I've written a script called DeDuper which can help remove unwanted duplicates. See this thread for background.
    tt2

  • Output says "The number of bytes in the file are 0" but the file has bytes

    Dear Java People,
    Why would an output say a file has 0 bytes when upon doing a search for the file in Windows Explorer it say the file has 1 -4 kbytes ?
    for example part of my output was :
    "the number of bytes in TryFile3.java are 0"
    caused by the following lines of code:
    System.out.println("\n" + contents[i] + " is a " +
    (contents.isDirectory() ? "directory" : "file\n") +
    " last modified on " + new Date(contents[i].lastModified())
    + "\nthe number of bytes in TryFile.java are " + myFile.length());
    thank you in advance
    below are the two program classes
    Norman
    import java.io.File;
    import java.io.FilenameFilter;
    import java.util.Date;
    public class TryFile3
       public static void main(String[] args)
           //create an object that is a directory
             File myDir =
            new File("C:\\Documents and Settings\\Gateway User\\jbproject\\stan_ch9p369");
              File myFile = new File(myDir, "TryFile3.java");
            System.out.println("\n" + myDir + (myDir.isDirectory() ? " is" : " is not")
            + " a directory.");
             System.out.println( myDir.getAbsolutePath() +
             (myDir.isDirectory() ? " is" : " is not") + " a directory.");
              System.out.println("The parent of " + myDir.getName() + " is " +
              myDir.getParent());
               //Define a filter for java source files Beginning with the letter 'F'
               FilenameFilter select = new FileListFilter("F", "java");
               //get the contents of the directory
               File[] contents = myDir.listFiles(select);
                //list the contents of the directory
             if(contents != null)
                 System.out.println("\nThe " + contents.length  +
                 " matching item(s) in the directory " + myDir.getName() + " are:\n " );
                 for(int i = 0; i < contents.length; i++)
                   System.out.println("\n" +  contents[i] + " is a " +
                   (contents.isDirectory() ? "directory" : "file\n") +
    " last modified on " + new Date(contents[i].lastModified())
    + "\nthe number of bytes in TryFile3.java are " + myFile.length());
    else {
    System.out.println(myDir.getName() + " is not a directory");
    System.exit(0);
    import java.io.File;
    import java.io.FilenameFilter;
    import java.util.Date;
    public class FileListFilter implements FilenameFilter
    private String name; // file name filter
    private String extension; // File extension filter
    public FileListFilter(String name, String extension)
    this.name = name;
    this.extension = extension;
    // static boolean firstTime = true;
    public boolean accept(File diretory, String filename)
    //the following line of code can be inserted in order to find out who called the method
    // if(firstTime)
    // new Throwable("starting the accept() method").printStackTrace();
    boolean fileOK = true;
    //if there is a name filter specified, check the file name
    if(name != null)
    fileOK &= filename.startsWith(name);
    //if there is an extension filter, check the file extension
    if(extension != null)
    fileOK &= filename.endsWith('.' + extension);
    return fileOK;

    System.out.println("\n" + contents + " is a " +
    (contents.isDirectory() ? "directory" : "file\n") +
    " last modified on " + new Date(contents.lastModified())
    + "\nthe number of bytes in TryFile.java are " + myFile.length());I haven't read any of your italicized code, but perhaps there is a good reason why you have "myFile.length()" and not "contents.length()" in this line of code?

Maybe you are looking for