Write Integer to file

Stuck. I've got six integers and I need them to be written to file, each with a new line and for them to overwrite the digits currently held on file. Help appreciated.

I had the same trouble when I started my project (writing stuff to files). But instead of writing new IO methods for every class of mine, I wrote one with a static method. This way it can be called from every class I have. If you want to use it here it is;
import java.io.*;
public class WriteThis
public static String fileName;
public static void WriteIt (String [] whatToWrite)
try
fileName = whatToWrite [0];
String writeOnLine;
FileWriter fw = new FileWriter (fileName);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
for (int i = 1; i < whatToWrite.length; i++)
writeOnLine = whatToWrite ["i"];//don't actually use the quotes,
//the whole page kept going to
//italics without them.
outFile.println (writeOnLine);
outFile.close ();
catch (IOException e)
String error = "There was an error";
The way you can use this is to convert your integers into a String array. In the first entry (yourArray [0]) put your filename ("myInts.dat" or whatever you want to call it). It then prints each array index on a new line for your. If you end up using it would you reply to this, just so I know if it is actually useable for everyone.
If you don't want this file saved in the same directory as your classes just pass the path you want it to save to ("C:\Program Files\My Program\here\") and it will save in here\.
To call it all you have to do is something like this:
String [] saving = {
     "myints.dat",
     caption.getText (),
     news.getText ()
WriteThis.WriteIt (saving);
except you will have to convert your integers into strings. Hope this works, and just watch that the formating is right, when I was previewing square braces were working like HTML brackets and parenthesis were working like square brackets.

Similar Messages

  • How to write in a file without erase it each time I want to write inside

    Hi
    My problem is to write in a unique file without erasing what I have written inside before.
    Because I use an Applet and I write some information in afile each time the user push a button but I want to keep all the information, beacause in my case I only have the last information i.e. the last time the user push the button.
    My code is:
    Below it is the code where I write in the file:
    writer2 = new BufferWriter("chemin.txt");
    methode = uneMethode;
    eps = unEps;
    n = unN;
    solExacte=uneSolExacte;
    y=z;
    Date time =new Date();
    Vector valeur = new Vector();
    valeur.add(new Double(eps));
    valeur.add(new Integer(n));
    valeur.add(new Integer(solExacte));
    valeur.add(new Integer(methode));
    String time_string = time.toString();
    valeur.add(new String(time_string));
    //writing to variables file
    BufferWriter writer = new BufferWriter("variables");
    writer.write(valeur);
    Now it is the class Bufferwriter:
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Vector;
    import java.io.File;
    public class BufferWriter {
    private String fileName;
    BufferedWriter w;
    public BufferWriter(String name) throws IOException {
    fileName=name;
    w=new BufferedWriter(new FileWriter(new File(fileName)));
    public void write(Vector v) throws IOException {
    String string;
    for (int i=0; i<5; i++) {
    string=((v.get(i)).toString());
    w.write(string,0, string.length());
    w.newLine();
    w.flush();
    public void close() throws IOException{
    close();}

    try
    w=new BufferedWriter(new FileWriter(fileName, true));
    The Constructor you want is ..
    FileWriter
    public FileWriter(String fileName,
    boolean append)
    throws IOException

  • Type to write in a file

    I want to write in a file
    1,1,1,1 where 1 is an int/integer optionally i have to write also 0(zero)
    my java ws (very simple, numeric output variable is input variable)have to return
    1. int variable
    or
    2. new Integer variable(so the object)??
    In the tutorial there is only string type!
    In xsd file, what type of variable i have to set?
    Thanks
    Ema

    Sorry but i can't understand why i have to work with string if i have int variables! Then I need to increment the value in the variable!
    I think that your write file web service cannot write int value!
    I 've created xsd file:
    <?xml version="1.0" encoding="UTF-8" ?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd"
    targetNamespace="http://TargetNamespace.com/Write"
    xmlns:tns="http://TargetNamespace.com/Write"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified" nxsd:encoding="US-ASCII" nxsd:hasHeader="true" nxsd:headerLines="1" nxsd:headerLinesTerminatedBy="${eol}" nxsd:stream="chars" nxsd:version="NXSD">
    <xsd:element name="genstep">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="Step1" type="xsd:int" nxsd:style="terminated" nxsd:terminatedBy="," nxsd:quotedBy="&quot;">
    </xsd:element>
    <xsd:element name="Step2" type="xsd:int" nxsd:style="terminated" nxsd:terminatedBy="," nxsd:quotedBy="&quot;">
    </xsd:element>
    <xsd:element name="Step3" type="xsd:int" nxsd:style="terminated" nxsd:terminatedBy="," nxsd:quotedBy="&quot;">
    </xsd:element>
    <xsd:element name="Step4" type="xsd:int" nxsd:style="terminated" nxsd:terminatedBy="${eol}" nxsd:quotedBy="&quot;">
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>
    and the variable genstep is correctly filled. But i cannot write it on a file po_%SEQ%.txt in the directory I specified!
    This is the bpel process write:
    <invoke name="Invoke_Write" partnerLink="WriteFile" portType="ns2:Write_ptt" operation="Write" inputVariable="Invoke_Write_Write_InputVariable"/>
    This is the write.wsdl:
    <definitions
    name="Write"
    targetNamespace="http://xmlns.oracle.com/pcbpel/adapter/file/Write/"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns="http://xmlns.oracle.com/pcbpel/adapter/file/Write/"
    xmlns:plt="http://schemas.xmlsoap.org/ws/2003/05/partner-link/"
    xmlns:jca="http://xmlns.oracle.com/pcbpel/wsdl/jca/"
    xmlns:imp1="http://TargetNamespace.com/Write"
    xmlns:hdr="http://xmlns.oracle.com/pcbpel/adapter/file/"
    >
    <import namespace="http://xmlns.oracle.com/pcbpel/adapter/file/" location="fileAdapterOutboundHeader.wsdl"/>
    <types>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" >
    <import namespace="http://TargetNamespace.com/Write" schemaLocation="schema_1.xsd" />
    </schema>
    </types>
    <message name="genstep_msg">
    <part name="genstep" element="imp1:genstep"/>
    </message>
    <portType name="Write_ptt">
    <operation name="Write">
    <input message="tns:genstep_msg"/>
    </operation>
    </portType>
    <binding name="Write_binding" type="tns:Write_ptt">
    <jca:binding />
    <operation name="Write">
    <jca:operation
    PhysicalDirectory="C:\prova"
    InteractionSpec="oracle.tip.adapter.file.outbound.FileInteractionSpec"
    FileNamingConvention="po_%SEQ%.txt"
    OpaqueSchema="false" >
    </jca:operation>
    <input>
    <jca:header message="hdr:OutboundHeader_msg" part="outboundHeader"/>
    </input>
    </operation>
    </binding>
    <service name="Write">
    <port name="Write_pt" binding="tns:Write_binding">
    <jca:address location="eis/FileAdapter" />
    </port>
    </service>
    <plt:partnerLinkType name="Write_plt" >
    <plt:role name="Write_role" >
    <plt:portType name="tns:Write_ptt" />
    </plt:role>
    </plt:partnerLinkType>
    </definitions>
    Thanks,
    Ema

  • Writing integer to file error

    Hey
    Im trying to write an integer to a file, but it writes an whole ohter number than variable contains. I know this because i do i System.out.println on the variable and it prints the correct number. Why does the write function write anohter number? For example the print shows 50 but the write functions write " 2" to file.
    Here i call the write:
    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                          
            String file = "C:\\Users\\Jesper\\Documents\\NetBeansProjects\\Katrinelund_v0.16\\secure\\checkNewOrder.txt";
            control.deleteFile(file);
            control.createFile(file);
            int currentOrder = control.getCurrentOrderNumber();
            System.out.println(currentOrder);
            control.setWriteToFile(file, currentOrder);
            quit();       
        } Here is the write function:
    public void writeToFile(String fileDestination, int WhatToWrite){       
            FileOutputStream fos;
            DataOutputStream dos;
            try {
                File file= new File(fileDestination);
                fos = new FileOutputStream(file);
                dos = new DataOutputStream(fos);
                dos.writeInt(WhatToWrite);
            } catch (IOException e) {
                e.printStackTrace();
        }

    jverd wrote:
    newark wrote:
    Try
    PrintWriter pw = new PrintWriter(new PrintWriter(file), true);
    You wanna rethink that maybe? :-)Probably. First I just put the file in, then realized that the autoflush constructor needs a writer, not a file. So I put a BufferedWriter in, but then realized BufferedWriter doesn't take a file either. Then I was all confused, and meant to use a FileWriter but put PrintWriter instead.
    So how about
    PrintWriter pw = new PrintWriter(new FileWriter(file), true);In short, I hate nested readers/writers and think that if you ever have to use them, there's a flaw in the IO system.

  • How to create and write in a file

    Hello Gurus,
    I am creating a file based on the date and time and writing into that. But, I am still getting exception error and all. Kindly, please let me know.
    thanks for all the help...j
    Error:-
    C:\Usage\JavaFiles>java filename "abc"
    Exception in thread "main" java.io.FileNotFoundException:Detail09-2003-
    03:28:04.doc (The system cannot find the file specified)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:176)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
    at TowerDetail.main(TowerDetail.java:30)
    Code sample:-
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    public class TowerDetail{
    public static void main (String[] args) throws IOException{
    String userName = "user";
    String passwd = "pwd";
    String con_db = "jdbc:odbc:datasource";
    String ssn = args[0];
    Vector results = new Vector();
    Connection con = null;
    CallableStatement cstmt = null;
    java.util.TimeZone tz = java.util.TimeZone.getTimeZone("EST");
    java.util.Date now = new java.util.Date();
    DateFormat df = new SimpleDateFormat("MM-dd-yyyy-hh:mm:ss");
    df.setTimeZone(tz);
    String result = df.format(now);
    String fileName = "Detail"+result+".doc";
    File inputFile = new File(fileName);
    FileOutputStream fos = new FileOutputStream(inputFile);
    PrintWriter pw = new PrintWriter(fos);
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    }catch (Exception e) {
    System.out.println("JDBC Error: "+e.getMessage());
    return;
    try{
    con = DriverManager.getConnection(con_db, userName, passwd);
    cstmt = con.prepareCall("{call dbo.sp_usage_detail(?)}");
    cstmt.setString(1, ssn.trim());
    ResultSet rs = cstmt.executeQuery();
    pw.println("Report "+result);
    pw.println("------------------------------------------------------------------------------------
    while(rs.next()){
    .... write in the file...
    pw.println("------------------------------------------------------------------------------------
    pw.close();
    System.out.println("Your file Detail"+result+".doc is ready!!!");
    cstmt.close();
    con.close();
    }catch(SQLException ex){
    System.out.println("SQLException: ");
    System.out.println(ex.getMessage());
    }catch(NullPointerException e){
    System.out.println("Null Pointer Exception: ");
    System.out.println(e.getMessage());

    Now, I got out of the command prompt and reentered. I didn't set any classpath or anything. I have created a subdir \archive in the C:\ and writing an output file [DetailTower.....doc")into that.
    The DetailTower.class is in C:\Detail\ProjectClass dirctory.
    Now at,
    C:\Detail\ProjectClass\java -classpath . DetailTower "abc"
    I am getting this error:-
    C:\Detail\ProjectClass>java -classpath . DetailTower "999999"
    Exception in thread "main" java.io.FileNotFoundException: c:\archive\DetailTower09-10-2003-06:23:40.doc (The system cannot find the file specified)at java.io.FileOutputStream.open(Native Method)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:176)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
            at Detail.main(DetailTower.java:32)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Write to spreadsheet file.vi is storing data in one row only.

    The 8 points of data is going into one column in the spreadsheet. In the "Write to spreadsheet file string.vi" how do I write the 8 points to one row for each cycle?
    I got this VI from NI's web a couple of years ago and forgot how to modify this part. I usume it is within the write file.vi.
    Thank you in advance
    Skip

    I just reread your original post and the way the "Write to Spreadsheet File.vi" that ships with LV works by default is to put 1D arrays into rows. I read your post backwards and told you how to put the data in a column. Sorry.
    In any case, perhaps you need to make sure the Transpose input ISN'T true, and that the delimiter IS a tab.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • How can I read, millions of records and write as *.csv file

    I have to return some set of columns values(based on current date) from the database (could be million of record also) The dbms_output can accomodate only 20000 records. (I am retrieving thru a procedure using cursor).
    I should write these values to a file with extn .csv (comma separated file) I thought of using a utl_file. But I heard there is some restriction on the number of records even in utl_file.
    If so, what is the restriction. Is there any other way I can achive it? (BLOB or CLOB ??).
    Please help me in solving this problem.
    I have to write to .csv file, the values from the cursor I have concatinated with "," and now its returning the value to the screen (using dbms_output, temporarily) I have to redirect the output to .csv
    and the .csv should be in some physical directory and I have to upload(ftp) the file from the directory to the website.
    Please help me out.

    Jimmy,
    Make sure that utl_file is properly installed, make sure that the utl_file_dir parameter is set in the init.ora file and that the database has been re-started so that it will take effect, make sure that you have sufficient privileges granted directly, not through roles, including privileges to the file and directory that you are trying to write to, add the exception block below to your procedure to narrow down the source of the exception, then test again. If you still get an error, please post a cut and paste of the exact code that you run and any messages that you received.
    exception
        when utl_file.invalid_path then
            raise_application_error(-20001,
           'INVALID_PATH: File location or filename was invalid.');
        when utl_file.invalid_mode then
            raise_application_error(-20002,
          'INVALID_MODE: The open_mode parameter in FOPEN was
           invalid.');
        when utl_file.invalid_filehandle then
            raise_application_error(-20002,
            'INVALID_FILEHANDLE: The file handle was invalid.');
        when utl_file.invalid_operation then
            raise_application_error(-20003,
           'INVALID_OPERATION: The file could not be opened or
            operated on as requested.');
        when utl_file.read_error then
            raise_application_error(-20004,
           'READ_ERROR: An operating system error occurred during
            the read operation.');
        when utl_file.write_error then
            raise_application_error(-20005,
                'WRITE_ERROR: An operating system error occurred
                 during the write operation.');
        when utl_file.internal_error then
            raise_application_error(-20006,
                'INTERNAL_ERROR: An unspecified error in PL/SQL.');

  • Write to measurement file at every n iterations

    Hi guys,
    I would like some help with saving data in labview 2010 SP1 (base development system). I am using a "Write to measurement fil express VI" inside a while loop and the data out from the DAQmn Read is wired to the signal in of the "Write to measurement fil express VI".
    The way I have wired it is the VI saves the data as a text file after it has recorded 100 samples (the nuber of samples to read in this case was set to 100). I would like to know if there is a way to control the rate at which the express VI saves the data. As in, I want the express VI to save the data at specified time interval or at every nth iteration. I have attached the main VI and its 2 sub-VIs for reference. Please let know if anyone can help me resolve this issue. Thank you for your time and inputs in this regard.
    Raj

    Robert,
    First, you must understand that the above code resides inside a loop. The blue square i terminal is known as the iteration terminal. It provides the current loop iteration count, starting from zero.
    The first input (x) to the Quotient & Remainder Function comes from this iteration count (i) terminal of the loop.
    The second input (y) to the Quotient & Remainder Function comes from the control N.
    We wish to write to the measurement file every N iterations of the loop. If we take our current iteration count (i) and divide by our desired N, every Nth iteration of the loop, the remainder will be zero. For all other iterations, the remainder will be non-zero.
    That being said, we check the remainder and compare it to zero. If it is zero, we will send a True value to the Enable terminal on the Write To Measurement File Express VI. Any time a True value is sent, we will write to file. Anytime a False value is sent, nothing will be written to the file.
    The green new_file input on the Write To Measurement File Express VI is used when the "Save to series of files (multiple files)" radio button is selected in the Configure dialog box of this Express VI. When "Save to one file" is selected, this option does not apply, and so it is not included in the input list, which is why you are not seeing this.
    This new_file input is used to tell the Write To Measurement File Express VI when to start writing to a new file.
     

  • WIN7 x64 Home Basic, 0x80070013 when trying to write or delete files. Disk is write protected.

    Hi,
    My SD card reader is not able to write or delete and format sd cards.
    WIN7 x64 Home Basic, 0x80070013 when I trying to write or delete files. When I trying to format I can see a message that disk is write protected. 
    The card is not locked, it's work in Lenovo Idea Pad s10 without any problem, It's also work in my Pentax camera.
    I'm almost sure that the problem is software, but can't find solution.
    Could Any one help me please?
    Laptop is new, 8 days in use. 

    I have network shutdown 2.0.1 installed and the pcns process normally would be abend in 1 or 2 minute's time. What could be the problem ? Consider to upgrade the network shutdown to 2.2.1 version. Could the problem be resolved in new version ? Any precaution needs to be taken when installing the new version ?
    Terence.

  • Need to write/delete a file (token) to/from user's home directory

    I want to build a class that runs on Windows/Unix clients. It needs to get to users' home directories (both environments) and write the token on login, delete it on logout.
    What method (or code snipet) would get a user's home directory?
    What method (or code snipet) would write/delete a file from it?
    Thanks much

    Even if you are not writing an Applet, this is applicable. But I thot if you were, you might need this.
    See 'SignedAppletDemo.java'
    http://developer.java.sun.com/developer/technicalArticles/Security/Signed/

  • How to combine both DAQ AI signal, write and read file in single VI

    Hi
     I am the new user of LabVIEW version 7.1 for testing automation application. I have to measure 33 signals ( mostly analog like temp, pressure, etc...) from NI USB 6210 DAQ system and write in master file for future verfication.From real data or from master file back up have to write  one more file if only the signal reaches steady state , which will used for analysis and same signals to be read from this file parallely & make a waveform and/or table display format.
    Pl. help me to shortout this problem 
    note: I have plan to ugrade labVIEW version 2011 shortly, so let me know doing parrel acquistion write and read file for data analysis in same VI in version 7.1...... 

    Parallel operations in LabVIEW are very simple.  Just code it in parallel and it will work.
    Try taking a look at some of the examples in the NI Example Finder (Help > Find Examples).  There you will find example for writing to and reading from files, as well as data acquistion in parallel with other operations.
    You might need a producer/consumer architecture is you are acquiring data very quickly.
    Chris
    Certified LabVIEW Architect
    Certified TestStand Architect

  • Some Doubts in write into spreadsheet file function

    hi,
    i have some problem with writing the values into excel file...if \ found then the values after will write the values in next rows...
    for eg. if i give 78/58\46/86 then i will write as in picture i hav attached..
    Attachments:
    Mod 1.vi ‏23 KB
    Untitled.png ‏135 KB

    The Write to Spreadsheet File is not the same as writing to Excel -- for that, you should use the Report Generation Toolkit (and there have been a number of posts here, as well as examples that ship with LabVIEW).
    That being said, it is not clear (a) what you are trying to do, and (b) what is (or is not) happening.  The image you attached looks OK ...

  • The Microsoft Access database engine cannot open or write to the file in Report Builder 3.0

    I am trying to build a report in Report Builder 3.0.  I created the Data Source to point to my Excel file and the Data Set.  I drag a couple of fields on to the canvas and then choose Run.  I get the error:  "The Microsoft Access
    database engine cannot open or write to the file.  It is already opened exclusively by another user".  I am using the Excel driver.  Why am I getting this message?  How can I fix this?

    No, now I am getting the error message again.  It is quite long:
    ERROR [HY000] [Microsoft][ODBC Excel Driver] The Microsoft Access database engine cannot open or write to the file '(unknown)'. It is already opened exclusively by another user, or you need permission to view and write its data.
    ERROR [01S00] [Microsoft][ODBC Excel Driver]Invalid connection string attribute Trusted_Connection
    Please help

  • Hi am trying to save Data into a write to measurement file vi using a NI PXI 1042Q with a real time mode but it is not working but when i run it with uploading it into the PXI it save in to the file

    Hi am trying to save Data into a write to measurement file vi using a NI PXI 1042Q and DAQ NI PXI-6229 with a real time mode but it is not working but when i run it without uploading it into the PXI it save in to the file please find attached my vi
    Attachments:
    PWMs.vi ‏130 KB

     other problem is that the channel DAQmx only works at real time mode not on stand alone vi using Labview 8.2 and Real time 8.2

  • How to read the and Write the PDF file give me the solution

    Hi all,
    How to read the and Write the PDF file give me the solution
    My coding is
    import java.io.File;
    import com.asprise.util.pdf.PDFImageWriter;
    import com.asprise.util.pdf.PDFReader;
    import java.io.*;
    import java.io.FileOutputStream;
    public class example {
    // public example() {
         public static void main(String a[])
              try
              PDFReader reader = new PDFReader(new File("C:\\AsprisePDF-DevGuide.pdf"));
                   reader.open(); // open the file.
                   int pages = reader.getNumberOfPages();
                   for(int i=0; i < pages; i++) {
                   String text = reader.extractTextFromPage(i);
                   System.out.println("Page " + i + ": " + text);
    // perform other operations on pages.
    PDFImageWriter writer = new PDFImageWriter(new FileOutputStream("c:\\new11.pdf"));
                   writer.open();
                   writer.addImage("C:\\sam.doc");
                   writer.close();
                   System.out.println("DONE.");
    reader.close();
              catch(Exception e){System.out.println("error:"+e);
              e.printStackTrace();
    I get the pdf content then it returns the string value but ther is no option to write the string to PDF, and we only add a image file to PDF,but i want to know how to wrote the string value to PDF file,
    Please give response immtly
    i am waiting for your reply.
    thanks,
    Suresh.G

    I have some question flow
    How library to use this code.
    I try runing but have not libary.
    Please send me it'library
    Thank you very much!

Maybe you are looking for

  • Dreamweaver 8 - Problematic Broken Link Check

    On a regular basis I use Dreamweaver 8's broken link checker to convert relative links to absolute throughout single HTML files. Once upon a time, I could use the results pane to quickly replace all of the broken links. Ever since installing Dreamwea

  • Instrument control fundamentals

    Hi,       I need some help regarding instrument control.I want to control instruments uing labVIEW8.6.I'm new to the job.can anybody tell me what are all the requirements(like installing instrument divers, labview 8.6) inorder to control an instrumen

  • Activation of sapmail

    hi , we have just activated out sap business workplace, the mail we are sending to intranet id its working but when we are sending the same mail to external network , it's not working, so, can any one give suggestion or related program through we can

  • Powerpoint 2007 with Acrobat X Standard

    Hi all, my Acrobat version is 10.1.4. now my problem is I want save my ppt in pdf with encrytion, current ppt got 194 slide, when converting at slide 111, ms office ppt pop out appcrash. I tries reinstall ms office and acrobat and both program update

  • Every time i try to play a video on the apple site it says i'm missing a plug in. what plug in am i missing?

    Everytime I try to play a video on the apple site it says I'm missing a plug in. Can some one tell me what plug in I'm missing? Thank you!