File length question...

I'm a java student, and I'm having problems. I have to take the information from a Vector, and write it to a disk file on the A drive. Then I have to be able to read the file back into the Vector for processing. I can't find any info on how to do that. I've seen 347 different ways to CREATE a file that isn't already there... but how do I set the length to be written, and then how do I read and transfer the data back into the Vector? Any help would be greatly appreciated!! I'm so frustrated that my wife is worried I'm going to break my hand from punching the monitor so hard...

I will continue my search for information, and maybe I'll find it. Maybe it
has something to do with using a Vector instead of an ArrayList or
something...Nope, a Vector will do just as fine as an ArrayList. You shouldn't be
afraid to write some toy code and play with it. Here's a bit I type in on
the fly:public abstract class Person implements Serializable {
   public abstract void speak();
public class Fred extends Person {
   public void speak() { System.out.println("Wilmaaaa!!!!");
public class Barny extends Person {
   public void speak() { System.out.println("Jeez Fred ...");
public class Dino extends Person {
   public void speak() { System.out.println("Arf! Arf! Arfarfarf!");
}The following class attempts to create a List (or Vector if you want),
sticks three persons in it and tries to write the entire thing to a file:public class Test {
   static public void main(String[] args) {
      ObjectOutputStream oos= null;
      List<Person> list= new ArrayList<Person();
      list.add(new Fred());
      list.add(new Barney());
      list.add(new Dino());
      try {
         FileOutputStream fos= new FileOutputStream("test.data");
         oos= new ObjectOutputStream(fos);
         oos.writeObject(list);
      catch (Exception e) { e.printStackTrace(); }
      finally {
         try { oos.close(); } catch (Exception e) { /* muffle */ }
      ObjectInputStream ois= null;
      try {
         FileInputStream fis= new FileInputStream("test,data")l
         ois= new ObjectInputStream(fis);
         list= (List<Person>)ois.readObject();
         for (Person p : list)
            p.speak();
      catch (Exception e) { e.printStackTrace(); }
      finally {
         try { ois.close(); } catch (Exception e) { /* muffle */ }
}This was all from the top of my head, so no warranty etc. ;-)
You should get this up and running in no time; then play with it for a
while and see if you can understand what's happening.
kind regards,
Jos

Similar Messages

  • How can I check every 5 secs a file Length with Threads?

    As a matter of fact the subject is the main question.
    I need your HELP! PLEASEE!!

    import java.io.*;
    public class RFile implements Runnable {
         public static void main(String args[]) throws Throwable {
              RFile rf = new RFile(new File(args[0]));
              new Thread(rf).start();
         File file = null;
         public RFile(File f) {
              file = f;
         public void run() {
              try {
                   while (true) {
                        System.out.println(file.length());
                        Thread.sleep(5000);
              } catch (Throwable err) {};
    }

  • File.length()

    I have the following questions:
    when I read File.length() of bytes of data, Does the data consist of end of file charactor?
    thanks
    mark ma

    atleast, on my windows 2000 machine it doesn't...
    import java.io.*;
    public class Test {
      public static void main(String args[]) {
        try {
          String s = "This is a test";
          System.out.println(s.getBytes().length);
          PrintWriter pw = new PrintWriter(new FileOutputStream("test.txt"));
          pw.print(s);
          pw.close();
          File f = new File("test.txt");
          System.out.println(f.length());
        catch (Exception e) {
          e.printStackTrace();
    }

  • I got new hard driver for my MacBook I don't have the cd but I do have flash drive that has the software I need help because when I turn on my laptop it shows me a file with question mark how can I install the software from the flash driver?

    I got new hard driver for my MacBook I don't have the cd but I do have flash drive that has the software I need help because when I turn on my laptop it shows me a file with question mark how can I install the software from the flash driver?

    Hold down the Option key while you boot your Mac. Then, it should show you a selection of devices. Click your flash drive and it will boot from that.

  • Application server file length

    Hi,
    I am doing outbound proxy, where it si executed successfully and the file was placed in the appropriate location, but the file length is more than 255 characters , so i am unable to look into my whole file structure. My source file and target file structre is different some client related header is present in the target file. When i cheked in the sxmb_moni also my target message is not appearing. I have checked under inbound message flag and receiver grouping flag in both payloads it is showing my source structure. in response flag there is no payload folder. So finally iam unable to look at file whole file structure. Can any body suggest me what to do to look at my whole file structure. Even i try to download the file from application server even then also i am getting only till 255 characters of length. Kindly suggest some solution .
    Venkat

    Hi,
    I am doing outbound proxy, where it si executed successfully and the file was placed in the appropriate location, but the file length is more than 255 characters , so i am unable to look into my whole file structure. My source file and target file structre is different some client related header is present in the target file. When i cheked in the sxmb_moni also my target message is not appearing. I have checked under inbound message flag and receiver grouping flag in both payloads it is showing my source structure. in response flag there is no payload folder. So finally iam unable to look at file whole file structure. Can any body suggest me what to do to look at my whole file structure. Even i try to download the file from application server even then also i am getting only till 255 characters of length. Kindly suggest some solution .
    Venkat

  • Problem with file length in jsp it is working in IE, not workig Firefox

    Hi,
    I'm upload a file from the browser. i'm calculating the length i'm not getting the length of the file.
    The below shown code is working perfectly in IE and not working in Firefox.
    FileUpload.html
    <DOCTYPE>
    <HTML>
    <HEAD>
    <TITLE>Retailmint Jobs - Registration Form</TITLE>
    </HEAD>
    <BODY>
    <form>
    <table>
    <tr><td>Upload Resume :</td>
    <td> <input>
       </td>
    </tr>
    </table>
    <input>
    </p>
    <p>  </p>
    </form>
    </BODY>
    </HTML>
    FileUploadSubmit.jsp
    <page>
    <page>
    <page>
    <html>
    <head><title>Retailmint- Submission</title></head>
    <body>
    <FileInputStream>
    </body>
    </html>
    I find an error in firefox browser is not taking the fully qualified path
    i.e: C:\Documents and Settings\Administrator\Desktop\if.doc
    In firefox it is taking if.doc only.
    please tell me the solution.
    Regards
    venkat

    Sorry for that
    here is the code:
    FileUpload.html
    <HTML>
    <HEAD>
    <TITLE>Retailmint Jobs - Registration Form</TITLE>
    <script language="Javascript" src="FileRead.js">
    </script>
    </HEAD>
    <BODY>
    <form name='subregiform' method="get" action ="FileuploadSubmit.jsp" >
    <table width="566" border="0" cellspacing="0" cellpadding="0">
    <tr><td width="197"align="right">Upload Resume :</td>
    <td width="369"> <input type="file" name="file" value ="" onchange ="javascript:fopen('file');"><br>
       </td>
    </tr>     
    </table><br>
    <input type="submit" name="submit" value="Submit">
    </strong></p>
    <p>  </p>
    </form>
    </BODY>
    </HTML>
    FileUploadSubmit.jsp
    <%@ page import="java.text.*"%>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <jsp:useBean id="DBase" class="dbconnection.DBconnection" scope="session" />
    <html>
    <head><title>Retailmint- Submission</title>
    </head>
    <body bgcolor="#e0e0e0">
    <%
    FileInputStream fis = new FileInputStream(request.getParameter("file"));
    len = (int)file.length();
                   System.out.println("length"+len);
    %>
    </body>
    </html>
    And tell me How to find the absolute path of a file in JSP or JAVA?

  • Problem with file length in jsp IE it is working Firefox it is not workig

    Hi,
    I'm upload a file from the browser. i'm calculating the length i'm not getting the length of the file.
    The below shown code is working perfectly in IE and not working in Firefox.
    FileUpload.html
    <DOCTYPE>
    <HTML>
    <HEAD>
    <TITLE>Retailmint Jobs - Registration Form</TITLE>
    </HEAD>
    <BODY>
    <form>
    <table>
    <tr><td>Upload Resume :</td>
    <td> <input>
       </td>
    </tr>
    </table>
    <input>
    </p>
    <p>  </p>
    </form>
    </BODY>
    </HTML>
    FileUploadSubmit.jsp
    <page>
    <page>
    <page>
    <html>
    <head><title>Retailmint- Submission</title></head>
    <body>
    <FileInputStream>
    </body>
    </html>
    I find an error in firefox browser is not taking the fully qualified path
    i.e: C:\Documents and Settings\Administrator\Desktop\if.doc
    In firefox it is taking if.doc only.
    please tell me the solution.
    Regards
    venkat

    Sorry for that
    here is the code:
    FileUpload.html
    <HTML>
    <HEAD>
    <TITLE>Retailmint Jobs - Registration Form</TITLE>
    <script language="Javascript" src="FileRead.js">
    </script>
    </HEAD>
    <BODY>
    <form name='subregiform' method="get" action ="FileuploadSubmit.jsp" >
    <table width="566" border="0" cellspacing="0" cellpadding="0">
    <tr><td width="197"align="right">Upload Resume :</td>
    <td width="369"> <input type="file" name="file" value ="" onchange ="javascript:fopen('file');"><br>
       </td>
    </tr>     
    </table><br>
    <input type="submit" name="submit" value="Submit">
    </strong></p>
    <p>  </p>
    </form>
    </BODY>
    </HTML>
    FileUploadSubmit.jsp
    <%@ page import="java.text.*"%>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <jsp:useBean id="DBase" class="dbconnection.DBconnection" scope="session" />
    <html>
    <head><title>Retailmint- Submission</title>
    </head>
    <body bgcolor="#e0e0e0">
    <%
    FileInputStream fis = new FileInputStream(request.getParameter("file"));
    len = (int)file.length();
                   System.out.println("length"+len);
    %>
    </body>
    </html>
    And tell me How to find the absolute path of a file in JSP or JAVA?

  • Problem with file length in jsp it is working in IE, not working Firefox

    Hi,
    I'm upload a file from the browser. i'm calculating the length i'm not getting the length of the file.
    The below shown code is working perfectly in IE and not working in Firefox.
    FileUpload.html
    <DOCTYPE>
    <HTML>
    <HEAD>
    <TITLE>Retailmint Jobs - Registration Form</TITLE>
    </HEAD>
    <BODY>
    <form>
    <table>
    <tr><td>Upload Resume :</td>
    <td> <input>
       </td>
    </tr>
    </table>
    <input>
    </p>
    <p>  </p>
    </form>
    </BODY>
    </HTML>
    FileUploadSubmit.jsp
    <page>
    <page>
    <page>
    <html>
    <head><title>Retailmint- Submission</title></head>
    <body>
    <FileInputStream>
    </body>
    </html>
    I find an error in firefox browser is not taking the fully qualified path
    i.e: C:\Documents and Settings\Administrator\Desktop\if.doc
    In firefox it is taking if.doc only.
    please tell me the solution.
    Regards
    venkat

    I agree with your words
    sorry for the code pasting.
    Here is the code:
    FileUpload.html
    <HTML>
    <HEAD>
    <TITLE>Retailmint Jobs - Registration Form</TITLE>
    </HEAD>
    <BODY>
    <form name='subregiform' method="get" action ="FileuploadSubmit.jsp" >
    <table width="566" border="0" cellspacing="0" cellpadding="0">
    <tr><td width="197"align="right">Upload Resume</td>
    <td width="369"> <input type="file" name="file" value ="" >
    </td>
    </tr>     
    </table>
    <input type="submit" name="submit" value="Submit">
    </form>
    </BODY>
    </HTML>
    FileUploadSubmit.jsp
    <%@ page import="java.text.*"%>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <html>
    <head><title>Retailmint- Submission</title>
    </head>
    <body bgcolor="#e0e0e0">
    <%
    FileInputStream fis = new FileInputStream(request.getParameter("file"));
    len = (int)file.length();
    System.out.println("length"+len);
    %>
    </body>
    </html>
    And how to find the absolute path of a file in jsp or java
    Edited by: venkat.k on Sep 17, 2007 10:12 PM

  • File length different for a copied file. Or use checksum

    Hi
    I am making a backup of a file before doing some writes to the original.
    I first check it out of source control, then make a copy using:
    public static void backupFile(File f)
    try{
    File backup = new File(f.getPath()+"_BACKUP");
    if (!backup.exists()) {
    if (!backup.createNewFile()) {
    Logger.getLogger().log("Could not create "+backup.getPath());
    SystemTools.copyFile(f,backup);
    } catch (Exception e)
    Logger.getLogger().log("Error backing up "+f.getPath()+ ": "+e);
    public static synchronized void copyFile(File from, File to) throws Exception
    if (!from.exists() || !from.isFile())
    throw new Exception ("copyFile Error: checking 'from' file!");
    if (!to.exists())
    if(!to.createNewFile())
    throw new Exception ("copyFile Error: creating 'to' file!");
    FileInputStream in=new FileInputStream(from);
    FileOutputStream out=new FileOutputStream(to);
    int length;
    byte[] buffer=new byte[256];
    while((length=in.read(buffer))!=-1) {       
    out.write(buffer, 0, length);
    in.close();
    out.close();
    After writing has finished, I need to see if the file is different to the backup..
    If so, I need to check it into source control.
    I wanted to use a checksum, but couldn't find an example that actually worked!!! Therefore I did a quick tool:
    public static boolean isBackupIdenticalToOrig(File f) throws Exception {
    File bu = new File(f.getPath()+"_BACKUP");
    Logger.getLogger().log("Lengths: New/Backup"+f.length()+"/"+bu.length());
    if (bu.length()!=f.length())
    return false;
    // Have the same lengths, so we can compare!!
    BufferedInputStream f_in = null;
    BufferedInputStream bu_in= null;
    f_in =new BufferedInputStream (new FileInputStream (f));
    bu_in =new BufferedInputStream (new FileInputStream (bu));
    for (int i=0;i<f.length();i++)
    int c = f_in.read();
    int d = bu_in.read();
    if (c!=d)
    Logger.getLogger().log(""+f.getName()+" has been modified");
    return false;
    Logger.getLogger().log(""+f.getName()+" has not been modified");
    return true;
    The problem is in that the File.length() method is returning different values for the backup file, than for the original, even if identical!
    For example:
    10/15/2002 10:22:05: Lengths: New/Backup413/402
    10/15/2002 10:22:06: Lengths: New/Backup397/386
    10/15/2002 10:22:07: Lengths: New/Backup191/185
    All the new files are longer that the backup, but the contents are exactly the same! Is there some WIN32 'extras' in the file that's causing a problem here???
    In each of the cases, if I open the new(Longer) file in a good editor, I can see that the lengths are correct. But no extra characters existed in the new file compared to the backup!!
    Any ideas would be most appreciated
    Cheers
    Chris

    10 and 13 are CR(carriage return) and LF(linefeed) - this is normal for a Windows file. Use this copy routine; it works.
       // copyFile -  input: inFile -  path to source file
       //                    outFile - path to copy file to (including filename)
       //                    bRemoveSource - true removes the source files, false leaves them intact
       //             returns: void
       public static void copyFile(String inFile, String outFile,boolean bRemoveSource) throws IOException
          FileInputStream fin     = null;
          FileOutputStream fout   = null;
          boolean bCanWrite       = false;
          boolean bDeleted        = false;
          // To preserve date/time stamp
          File fTimeIn = new File(inFile);
          File fTimeOut = new File(outFile);
          long lTimeIn = fTimeIn.lastModified();
          try
            fin  = new FileInputStream(inFile);
            fout = new FileOutputStream(outFile);
            copyStream(fin, fout);
          finally
            try
              if (fin != null) fin.close();
            catch (IOException e) {}
            try
              if (fout != null) fout.close();
            catch (IOException e) {}
          fin.close();
          fout.close();
          // Set out time to in time
          fTimeOut.setLastModified(lTimeIn);
          if (bRemoveSource == true)
             bCanWrite = fTimeIn.canWrite();
             if (bCanWrite)  {
                bDeleted = fTimeIn.delete();
       // copyStream (a helper function for copyFile) -  input: in  - file stream of source file
       //                                                       out - file stream of destination file
       //                                                returns: void
       // *** NOTE: This function is thread safe ***
       public static void copyStream(InputStream in, OutputStream out)  throws IOException
          // do not allow other threads to read from the
          // input or write to the output while copying is
          // taking place
          synchronized (in)  {
             synchronized (out)  {
                byte[] buffer = new byte[256];
                while (true)  {
                   int bytesRead = in.read(buffer);
                   if (bytesRead == -1)
                      break;
                   out.write(buffer, 0, bytesRead);
       }

  • HT1752 My MacBook on startup shows file with question mark ,, what now?

    My Mac shows file with question mark, what now.

    Press the power button down to force a emergency use only hardware shutdown.
    Press and hold the Option/alt key on the built in keyboard, boot the machine.
    If MacintoshHD appears, select it and click the arrow, then in System Preferences > Startup Disk reset that. Done.
    Sometimes a NVRAM reset is required then the above done again.
    Folder with question mark issue
    ..Step by Step to fix your Mac
    If MacintoshHD doesn't appear, or if it boots to gray screen or other issues, then it's more complicated of a fix, but once inside OS X then reset the Startup Disk.
    Gray, Blue or White screen at boot, w/spinner/progress bar
    ..Step by Step to fix your Mac
    You might need this if you don't have a recent backup and your problem is software related, Disk Utiltiy can't fix the drive and recommends you backup, erase and install.
    .Create a data recovery/undelete external boot drive
    If Disk Utility + Hardware Test shows no boot drive, then you have a dead drive or cable, or Mac issue.
    My computer is not working, is my personal data lost?

  • 1099 MISC 2011 file length

    Hi Experts
    This relates to 1099 MISC 2011 file length. We have applied SAP note 1666672 that pertains to 2011 changes.While the form print looks good, when i compared the file with P1220 ( The publication that specifies details on tax filing), i found that P1220 states that length of records should be 750 for the T and B records - however in my case i get only 746 characters
    I generated the file in txt and opened with excel and used LEN to count the length of the records
    Any suggestions? - Is there a further SAP note that is to be applied or a i  missing something on the DMEE side of it.
    Further is P1220 the Gospel to compare the correctness with.
    Thanks
    Swami

    HI swami,
    note 1666672 was updated  25th, please, review version 4.
    Also make sure you have applied the corrections or steps from notes
    1635493, 1673257 and and 1649356.
    Regards
    Madhu M

  • File.length issues

    I've been trying to make a terminal like program, but I've had issues detecting the file size. When I use file.length(), I get wildly different answers than use of the "du" unix command. Is this a bug in java? Mac OS X? Just me being an idiot?
    Thank you.

    They do different things for different purposes. du reports total disk usage, so it rounds up to the next block size. File.length() reports actual file size in bytes.

  • Unexpected problem; recently upgraded to version 3. Export of multiple tracks makes each file length same as longest file. Didn't do that in Vers2

    Unexpected problem; We rrecently upgraded to version 3. Export of multiple tracks in a multitrack session makes each file length same as longest file. Didn't do that in Vers 2 of soundtrack

    Hmm... Ok, so I took that project and tried importing it to a new project, still with no luck. Then I tried taking that project and creating a new timeline by dragging one of the stills to the new item icon so that I'd get whatever PrPro decided was the best timeline, and still no luck. Then I tried creating a new project and importing different footage and it worked. Tells me perhaps there's something wrong with the stills? I know not to use overly-large stills in a project, but they're all around 4k resolution or smaller... so surely that's not too big, right? 412 stills total 1.5GB which means an average of about 2.5 MB per file... certainly not too big. I even had a couple video clips in the timeline that were shot with a point-and-shoot still camera, and I tried taking those out just in case it was something in those, and still no success.
    So, ultimately this project got exported without CUDA, and I'm okay... but I also am wondering what caused the problem? I do a fair amount with stills (not a lot, but enough) and I need it to work... do I just go on with life, assuming that it was some weird fluke? Or do I try a complete wipe and reinstall of OS and Programs?
    Oh, one other tidbit... whenever PrPro crashed and closed, the application itself wouldn't close. I have to go into the program manager and force quit it...
    Thoughts? Recommendations?

  • File and question mark when starting

    Flashing file and question marl when i start my computer

    There are four general causes of this issue:
    1. The computer's PRAM no longer contains a valid startup disk setting when there aren't any problems with the disk itself. This can be checked for by pressing the Option key and seeing if the drive appears.
    2. The internal drive's directory structure has become damaged. This requires usage of an alternate bootable system to perform the repair.
    3. Critical system files have been deleted. This requires usage of an alternate bootable system to reinstall them.
    4. The internal drive has died or become unplugged. This is the most likely case if the computer took a sharp impact or there are unusual sounds coming from its location.
    (103563)

  • File.length() too slow?

    I'm working on an application that needs to process directory listings on network fileserver, looking for files and directories, and getting basic info about files found (size, last modified date).
    I'm trying to use java.io.File.list(java.io.FileFilter) with java.io.FileFilter returning file.isDirectory() or file.isFile() to get a list of just files or directories, and try to get the rest of file information later for each of the returned Files. However, when it gets to a directory with a lot of files (13000+), it seem to be unacceptably slow. I have tracked it down to File.length(), taking up to 80ms per file (!), which amounts to only about 13 files per second.
    It's not a problem of the platform (Win XP), directory listing contianing all information I need takes less than 3 seconds for this big directory, while getting the same through Java APIs (calling isDirectory(), isFile(), length() and lastModified() within the FileFilter callback ) takes ages.
    Is there a better way to get a directory listing, without being orders of magnitude slower than necessary? I can think of calling native dir command and parsing the output, but that is a mess...

    I have tracked this down to native implementation of File.length() - VC++ runtime function _stati64 which they use to get file length is too slow.
    Why dont they use Windows API? I have tested that getting file size using GetFileAttributesEx() is at least 50x faster than _stati64 for my file!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • Mail.app 5.3 crashes consistently on Mac OS 10.7.5

    Could somebody help me. Just a few days ago without any particular reason Mail.app started crashing regulary in 5-10 sec after launch. There is the crash log. Please help! Can't do anything without e-mails. Process:         Mail [16811] Path:        

  • Silly drop box question...

    All the years, I've been using a mac, and I have not figured this out still, and today was the last straw on figuring it out. (thxs for the rant!) Scenario : 2 macs in my home office, use dropbox in public folder to transfer files between 2 macs. I p

  • A few quick questions about my new MP3 pla

    Ok, I like to get to know anything I buy so I decided to come here and ask, I hope you dont mind answering (My MP3 player is the MuVo c00): ) In the instruction manual it says that play WMA file reduce the battery life of your player. Since convertin

  • Invoking a procedure/method via a string

    I know this is probably a long shot, but I will ask anyway... What I would like to do is invoke a procedure/method in a class/package which is not the current one by building a string which makes up the call and the parameters and then running it som

  • Regarding recording issue in MM03

    Hi All, I am trying to record MM03 transaction in SHDB. Please find below the sequence of screens: MM03 -> Basic data -> System Menu -> Services for object -> Create External Document. Now, the problem is when i am entering the system menu in SHDB, i