How to write list values to a text file?

Hi. Does anyone know how to write values stored in a List to a text file? I have a program that asks the user to enter a name and stores it in a list. The number of names in the list depends on how many times the user wants to enter a name. The problem is that my writeToFile method, which handles writing values to a text file, only writes one name and overwrites any previous names. How could I fix this so that it goes thru the list and writes every value to the file? Any hints would be appreciated!
peace
Chris
import java.util.*;
import java.io.*;
public class StoreNames
String name;
char answer;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public void anotherName(List a)throws IOException
System.out.println("Enter another name? (Y or N)");
answer = (char)System.in.read();
System.in.skip(2);
while(answer == 'Y' || answer == 'y')
inputName(a);
System.out.println("Enter another name? (Y or N)");
answer = (char)System.in.read();
System.in.skip(2);
if (answer == 'N' || answer == 'n')
System.out.println("Ok. GoodBye");
writeToFile(a);
//prompts user to input names
public void inputName(List a) throws IOException
System.out.print("Enter a name: ");
name = input.readLine();
a.add(name);
public void writeToFile(List a)throws IOException
PrintWriter output = new PrintWriter(new FileWriter("names.txt"));
output.print(name); //Problem area - handles only one line of input, overwrites previous input
output.close();

System.out is an instance of PrintStream (check the API documents for the System class to see this).
So the easiest way to convert from a "print to screen" class to a "print to file" class is to acquire a PrintStream that prints to a file, and use it exactly the same as you'd have used System.out...
So start with your console code...
        PrintStream out = System.out;
        for(int i = 0; i <10; i++){
            out.println("Number " +i);
        }Then you adapt to file code:
        FileOutputStream fos = new FileOutputStream("temp.txt");
        PrintStream out = new PrintStream(fos);
        for(int i = 0; i <10; i++){
            out.println("Number " +i);
        out.flush();
        out.close();Note that we flush the stream because for reasons of efficiency files aren't necessarily written to disk until you explicitly ask the system to do so (memory is fast, disks are slow, that's why).
Closing the stream releases system resources associated with it.
Actually, that's redundant, because close calls flush automatically, but I left it in for clarity.
Any use ?

Similar Messages

  • How to write a return in a text file.

    Hi, i am trying to write diferent lines into a text file, i write strings ending with \r\n but it doesn't work, how could i write in diferent lines?
    Thanks.

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt")));
    out.println("This is the first line");
    out.println("This is the second line");
    out.flush();
    out.close();Jesper

  • How to write the resultset into a text file

    how to write the resultset into a text file

    You can use the java.io.* package to write to files.
    API: http://java.sun.com/j2se/1.5.0/docs/api/java/io/package-summary.html
    Tutorial: http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • HOW TO WRITE AND READ FROM A TEXT FILE???

    How can I read from a text file and then display the contents in a JTextArea??????
    Also how can I write the contents of a JTextArea to a text file.
    Extra Question::::::: Is it possible to write records to a text file. If you have not idea what I am talking about then ignore it.
    Manny thanks,
    your help is much appreciated though you don't know it!

    Do 3 things.
    -- Look through the API at the java.io package.
    -- Search previous posts for "read write from text file"
    -- Search java.sun.com for information on the java.io package.
    That should clear just about everything up. If you have more specific problems, feel free to come back and post them.

  • How to write table values into a configuration file

    Im writing some values in the table, i want to save and load the table values,  how to save the table configuration into configuration file??

    Pls ignore my prev post, I cud not finish edit within 10 mins as req by the forum rule...
    If you are not able to access a VI front panel at all when another VI is called by the first VI, then probably the issue is that the VI properties is set to be Modal. Right click on the VI icon on the right top corner and select VI Properties. Under Window Appearance, you can click on Customise button and ensure the VI is not Modal (and Custom is selected). Before this, you need to ensure the calling VIs are also not set to Modal (I think if you set it to dialog, it will be Modal by def. So don't use that as well). If any of the parent VI is set to Modal and a subsequent child VI is in non-modal mode, then you will not be able to access the child VI front panel when called and may end up with forcing the program to close.
    Probably you may also need to have a different independant loop looking for the events. For this you may need to use Q structure as well, so that you can define a Q outside both loops, add elements to Q as and when the menu is selected within the loop for menu events, while the other loop works according to the Q elements it gets to remove.
    Hope that helps !

  • How to Write Waveform graph data to Text File with user option to do so

    So, I'm new to labview and am having trouble writing one program in particular.  I have a waveform graph that runs for 120 seconds generating a sine curve.  I am, however, having a difficult time getting the program to write the x and y coordinates into a text file.  I have attached what I have so far.  
    The first task I was assigned was to write a program that creates a snusoidal curve on the front pannel adding one data point each half second for 120 seconds.  The plot should only start when the user presses a start button.
    The next part involves giving the user an option to write the generated data to a spreadsheet file called "sine.txt".  The file name and location should be hardcoded.  The file should contain the x and y coordinates of each data point in columns separated by tabs, also known as delimited.
    I have spent several hours tweaking the attached program and I just can't seem to get it to work right.  Any suggestions would help at this point.
    Sincerely,
    A frustrated chemistry student whose research mentor is out of town
    Solved!
    Go to Solution.
    Attachments:
    Sinusoidal Curve (saving to excel).vi ‏45 KB

    First, you are not creating Excel files.  You are creating text files.  And it seems that your Write to file is already creating X (time) vs. Y (data curve) that is tab delimited.
    Everything else you are doing is just too complicated or a Rube Goldberg.
    All you need is the attached.
    Attachments:
    Sinusoidal_Curve_(saving_to_Text_file).vi ‏69 KB

  • How to Write log messages in a text file located in another machine

    Basically My application is distributed across two or more tomcat servers running in multiple machines.And I get a log4j logs in the respective machines.
    But I want a consolidated log message in a single machine.
    How do i get that done??
    Any samples?? Any clues??
    Any specific technoliges??

    Create an RMI application (for example) that writes the log, and let all logging calls call that remote application.
    Something like that is the only feasible way that doesn't require you to have a drive on the remote machine mapped to the local one (which causes its own problems as you could have multiple simultaneous write attempts...).

  • How to write from a linked list collection to a text file.

    Hi,
    I want to write my data in linked list collection to a text file.
    the following is the code of my linked list. how do i write it
    Iwant the data to be comma separated while writing it to a text file.
    please help.
    class MailList
            public static void main(String args[])
                    LinkedList m1 = new LinkedList();
                    m1.add(new Address("J.W.West", "11 Oak Ave",
                           "Urbana", "IL", "118011"));
                    m1.add(new Address("H.S.sandy", "1 k ve",
                           "Bana", "L", "18011"));
                    m1.add(new Address("K.Satish", "1 104 Clarence Street",
                            "Strathfield", "NSW", "135"));
                    Collections.sort(m1);
                    Iterator itr = m1.iterator();
                    while(itr.hasNext())
                            Object element = itr.next();
                            System.out.println(element + "\n");
    }

    look at the API for FileWriter.
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • How to write the value of JComboBox

    Hi All
    how to write the value of JComboBox, when the user selected?
    i.e. if i have text filed age and a JComboBox 20,30,40 and so on
    i want to save the age with the user selected item from JComboBox??
    any ideas

    Thanks for the useful link
    but what i need is how to write the JComboBox when it is appear in the line
    i.e if i have the following line
    Name Hana Age JComboBox Major JComboBox
    and i need to save all this line in a text file
    JLabel JTextfiled JLabel JComboBox JLabel JComboBox

  • SQL Loader-How to insert -ve & date values from flat text file into coloumn

    Question: How to insert -ve & date values from flat text file into coloumns in a table.
    Explanation: In the text file, the negative values are like -10201.30 or 15317.10- and the date values are as DDMMYYYY (like 10052001 for 10th May, 2002).
    How to load such values in columns of database using SQL Loader?
    Please guide.

    Question: How to insert -ve & date values from flat text file into coloumns in a table.
    Explanation: In the text file, the negative values are like -10201.30 or 15317.10- and the date values are as DDMMYYYY (like 10052001 for 10th May, 2002).
    How to load such values in columns of database using SQL Loader?
    Please guide. Try something like
    someDate    DATE 'DDMMYYYY'
    someNumber1      "TO_NUMBER ('s99999999.00')"
    someNumber2      "TO_NUMBER ('99999999.00s')"Good luck,
    Eric Kamradt

  • How do I overide the values in the text file

    I am reading a text file using loadvars, to get some values
    such as
    &yourid=123456 from the text file.
    How do I overide the values in the text file
    <PARAM NAME=movie VALUE="jamietrailer.swf?yourid=65432
    <---- this doesn't seem to work
    So I can change the values from the html file?

    I want to do this:
    # It should look like this:
    <PARAM NAME=movie VALUE= "movie.swf?text=hello">
    # Find the EMBED tag. Look for this:
    <EMBED src="/support/flash/ts/documents/movie.swf"
    # Again, replace the filename "movie.swf" with
    "movie.swf?text=hello".
    It should look like this:
    <EMBED
    src="/support/flash/ts/documents/movie.swf?text=hello"
    Is this supposed to overide the value I am reading using
    loadvars?
    or do I have to not read the value from the file if I am
    going to give it a value in html?

  • How to get summary columns in delimited text file

    How to get summary columns in delimited text file
    I am trying to generate a delimited text file output with delimited_hdr = no.The report is a Group above report with summary columns at the bottom.In the text file the headers are not getting repeated & thats ok.The problem is the summary data is getting repeated for each row of data.Is there a way where i will get all the data & summary data will get displayed only once.I have to import the delimited text file in excel spreadsheet.

    Sorry there were a typos :
    When I used desformat=DELIMITEDDATA with desttype=FILE, I get error "unknown printer driver DELIMITEDDATA". When you look for help, DELIMITED is not even listed as one of the values for DESTFORMAT. But if you scroll down and look for DELIMITER it says , this works only in conjuction with DESTFORMAT=DELIMITED !!!!!!??!! This is in 9i.
    Has this thing worked for anybody ? Can anyone please tell if they were able to suppress the sumary columns or the parent columns of a master-detail data for that matter ?

  • How to trigger data recording to a text file for multiple channels for a certain voltage threshold?

    I am working with 6 channels, from each of which I am obtaining voltage values ranging from 0.6-6 V.  I am using the DAQ Assistant to acquire and write the data to a text file.  However, I only want the data to be written to the text file when the difference in voltage (DeltaV) from one data point to another is greater than or equal to 0.04 V.  I am acquiring the data at a sampling rate of 64 Hz.  Any ideas on how to accomplish this?  I have attached my current VI. 
    Attachments:
    Data Triggering.vi ‏116 KB

    Faizah wrote:
    I am obtaining voltage values ranging from 0.6-6 V.  
    I only want the data to be written to the text file when the difference in voltage (DeltaV) from one data point to another is greater than or equal to 0.04 V.  
    Your code does not do what you describe above..
    I just want to make sure I understand your request...
    Let's say you have the following signal:
    0.00
    0.01
    0.00
    0.03
    0.02
    0.01
    0.03
    0.04
    0.07
    0.05
    0.08
    0.03  < delta greater than 0.04, so start recording
    0.11
    0.21
    0.45
    0.93
    2.87
    5.85
    5.86 < delta less than 0.04, so stop recording
    5.87
    5.89
    6.00  < delta greater than 0.04, so start recording
    5.85
    5.86  < delta less than 0.04, so stop recording
    etc..
    Is the above what you are describing?  
    Right now, your code does this:
    0.00
    0.01
    0.00
    0.03
    0.02
    0.01
    0.03
    0.04
    0.07
    0.05
    0.08
    0.03 
    0.11
    0.21
    0.45
    0.93
    2.87 < threshold greater than 1 so reset timer
    5.85 < threshold greater than 1 so reset timer
    5.86 < threshold greater than 1 so reset timer
    5.87 < threshold greater than 1 so reset timer
    5.89 < threshold greater than 1 so reset timer
    6.00  < threshold greater than 1 so reset timer
    5.85 < threshold greater than 1 so reset timer
    5.86  < threshold greater than 1 so reset timer
    4.35 < threshold greater than 1 so reset timer
    2.21 < threshold greater than 1 so reset timer
    1.09 < threshold greater than 1 so reset timer
    0.98 
    However, you did not provide a set start time  to the Elapse Time (I never use Express VI's so I'm not sure what will happen..) However, something does not appear correct with the logic.  I'd have to check.

  • How to write the nodevalue back to xml file?

    Hi, Everybody:
    These are two packages I used. javax.xml.parsers.*,org.w3c.dom.*
    Now I use "setNodeValue("abc") to set the node value to "abc". But it is not really saved back into XML file. It only change the node value in memory.
    How to write the changes back to XML file? Thank you very much for your help.
    Michelle

    * Version : 1.00
    * File Purpose : Given the xml file loads into dom and recreate the file with the updated values.
    * Developer : Kashif Qasim : 25/july/04
    * Modify detail :
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import org.w3c.dom.*;
    import org.apache.xerces.parsers.DOMParser;
    import org.apache.xerces.*;
    public class XMLWriter
    private String displayStrings[] = new String[5000];
    private int numberDisplayLines = 0;
    private Document document;
    //private final Node c;
    public synchronized void displayDocument(String uri,Vector UpdatedValues,String getTaskID)
    try {
    DOMParser parser = new DOMParser();
    parser.parse(uri);
    document = parser.getDocument();
    display(document, "",UpdatedValues);
    } catch (Exception e) {
    e.printStackTrace(System.err);
    ReadXmlConfig objReadXmlConfig = null;
    FileWriter filewriter = null;
    try {
    filewriter = new FileWriter(uri);
    for(int loopIndex = 0; loopIndex < numberDisplayLines; loopIndex++){
    filewriter.write(displayStrings[loopIndex].toCharArray());
    //System.out.println("displayStrings[loopIndex].toCharArray() "+displayStrings[loopIndex].toString());
    //filewriter.write("\n");
    filewriter.close();
    System.gc();
    objReadXmlConfig = new ReadXmlConfig();
    objReadXmlConfig.ITSLog("File updated for "+getTaskID+" succesfully, file is closed now ");
    } catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
    objReadXmlConfig = new ReadXmlConfig();
    objReadXmlConfig.ITSErrorLog("File updated FAILED for "+getTaskID+". Reason for file error "+e.toString());
    }finally {
    if (filewriter != null) {
    System.out.println("Closing File");
    objReadXmlConfig =null;
    try{
    filewriter.close();
    }catch(IOException e){
    System.err.println("Caught IOException: " + e.getMessage());
    } else {
    System.out.println("File not open");
    private void display(Node node, String indent, Vector UpdtRecs)
    if (node == null) {
    return;
    int type = node.getNodeType();
    NodeList nodeList = document.getElementsByTagName("QueryParm");
    int TotalRecs = UpdtRecs.size();
    switch (type) {
    case Node.DOCUMENT_NODE: {
    displayStrings[numberDisplayLines] = indent;
    displayStrings[numberDisplayLines] +=
    "<?xml version=\"1.0\" encoding=\""+
    "UTF-8" + "\"?>";
    numberDisplayLines++;
    displayStrings[numberDisplayLines] += "\n";
    display(((Document)node).getDocumentElement(), "",UpdtRecs);
    break;
    case Node.ELEMENT_NODE: {
    if(node.getNodeName().equals("QueryParm")) {
    for(int i =0 ; i< nodeList.getLength() ; i++)
    Node nodeQry = nodeList.item(i);
    NamedNodeMap nnp = nodeQry.getAttributes();
    for(int j= 0 ; j < nnp.getLength() ; j++)
    Attr atr = (Attr) nnp.item(j);
    if(atr.getName().equalsIgnoreCase("value_"+(i+1)))
    //System.out.println(atr.getName() +" : " + atr.getNodeValue() );
    atr.setNodeValue(UpdtRecs.get(i).toString());
    displayStrings[numberDisplayLines] = indent;
    displayStrings[numberDisplayLines] += "<";
    displayStrings[numberDisplayLines] += node.getNodeName();
    int length = (node.getAttributes() != null) ?
    node.getAttributes().getLength() : 0;
    Attr attributes[] = new Attr[length];
    for (int loopIndex = 0; loopIndex < length; loopIndex++) {
    attributes[loopIndex] = (Attr)node.getAttributes().item(loopIndex);
    for (int loopIndex = 0; loopIndex < attributes.length; loopIndex++) {
    Attr attribute = attributes[loopIndex];
    displayStrings[numberDisplayLines] += " ";
    displayStrings[numberDisplayLines] += attribute.getNodeName();
    displayStrings[numberDisplayLines] += "=\"";
    displayStrings[numberDisplayLines] += attribute.getNodeValue();
    displayStrings[numberDisplayLines] += "\"";
    displayStrings[numberDisplayLines]+=">";
    numberDisplayLines++;
    NodeList childNodes = node.getChildNodes();
    if (childNodes != null) {
    length = childNodes.getLength();
    indent += " ";
    for (int loopIndex = 0; loopIndex < length; loopIndex++ ) {
    display(childNodes.item(loopIndex), indent,UpdtRecs);
    break;
    case Node.CDATA_SECTION_NODE: {
    displayStrings[numberDisplayLines] = "";
    displayStrings[numberDisplayLines] += "<![CDATA[";
    displayStrings[numberDisplayLines] += node.getNodeValue();
    displayStrings[numberDisplayLines] += "]]>";
    numberDisplayLines++;
    break;
    case Node.TEXT_NODE: {
    displayStrings[numberDisplayLines] = "";
    String newText = node.getNodeValue().trim();
    if(newText.indexOf("\n") < 0 && newText.length() > 0) {
    displayStrings[numberDisplayLines] += newText;
    displayStrings[numberDisplayLines] += "\n";
    numberDisplayLines++;
    break;
    case Node.PROCESSING_INSTRUCTION_NODE: {
    displayStrings[numberDisplayLines] = "";
    displayStrings[numberDisplayLines] += "<?";
    displayStrings[numberDisplayLines] += node.getNodeName();
    String text = node.getNodeValue();
    if (text != null && text.length() > 0) {
    displayStrings[numberDisplayLines] += text;
    displayStrings[numberDisplayLines] += "?>";
    displayStrings[numberDisplayLines] += "\n";
    numberDisplayLines++;
    break;
    if (type == Node.ELEMENT_NODE) {
    displayStrings[numberDisplayLines] = indent.substring(0,
    indent.length() - 4);
    displayStrings[numberDisplayLines] += "</";
    displayStrings[numberDisplayLines] += node.getNodeName();
    displayStrings[numberDisplayLines] += ">";
    displayStrings[numberDisplayLines] += "\n";
    numberDisplayLines++;
    indent += " ";
    public static void main(String args[])
    Vector xmlValue = new Vector();
    xmlValue.add(0,"Kashif");
    xmlValue.add(1,"Qasim");
    //displayDocument("NewMediation.xml",xmlValue);
    <?xml version="1.0" encoding="UTF-8"?>
    <Mediation>
    <Task1>
    <Source>
    <SourceDriver>com.microsoft.jdbc.sqlserver.SQLServerDriver</SourceDriver>
    <SourceConnection>jdbc:microsoft:sqlserver://10.2.1.58:1433;DatabaseName=MTCVB_HDS;</SourceConnection>
    <SourceUser>sa</SourceUser>
    <SourcePassword>sa</SourcePassword>
    <Table>
    <SourceTable>t_Agent</SourceTable>
    <SourceQuery><![CDATA[SELECT SkillTargetID,PersonID,PeripheralID,EnterpriseName,PeripheralNumber,Deleted,TemporaryAgent,AgentStateTrace,ChangeStamp FROM t_Agent where SkillTargetID > {value_1} order by SkillTargetID]]>
    </SourceQuery>
    <SourceParm BusinessRule="" ColumnName="SKILLTARGETID" ColumnNumber="1" DataType="Numeric" DefaultValue="0" Format="mm/dd/yyyy xx:xx:xx XX">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="PERSONID" ColumnNumber="2" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="PERIPHERALID" ColumnNumber="3" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="ENTERPRISENAME" ColumnNumber="4" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="PERIPHERALNUMBER" ColumnNumber="5" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="DELETED" ColumnNumber="6" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="TEMPORARYAGENT" ColumnNumber="7" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="AGENTSTATETRACE" ColumnNumber="8" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <SourceParm BusinessRule="" ColumnName="CHANGESTAMP" ColumnNumber="9" DataType="String" DefaultValue="" Format="">
    </SourceParm>
    <QueryParm FldName_1="SkillTargetID" FldType_1="Number" value_1="0">
    </QueryParm>
    </Table>
    </Source>
    </Task1>
    </Mediation>
    The QueryParm values are updated thru this code :)
    Hope it helps u ...

  • How to read the content of a text file (by character)?

    Guys,
    Good day!
    I'm back just need again your help. Is there anyone knows how to read the content of a text file not by line but by character.
    Please help me. Thank you so much in advance.
    Jojo

    http://java.sun.com/javase/6/docs/api/index.html
    package java.io
    InputStream.read(): int
    Reads the next byte of data from the input stream.
    Implementation:
    InputStreamReader
    An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

Maybe you are looking for

  • Can't access game center using nickname from second account

    I have two Apple IDs associated with two different e-mail addresses.  I set up a game center account with one address and another account with the second address and different ID.  After my ipad had to be reset following a crash during the upgrade to

  • Where is the "Show Duplicates" functions in iTunes 11?

    I recently upgraded to the new version of iTunes and can't find the "show duplicate" options. This is one of the main reasons I don't upgrade to the new iTunes, because of this kind of stuff - missing functionality that I use on a regular basis... An

  • Colorprofil for 24 imac here

    Hi there, this is for us with the uneven brightness/color issue of the imac screen. I did a profil with coloreyes soft/spider hardware. Gamma L* D65 Very Important: Set yout imac to the brightest Level! The profile dimms the brightness down to 200cd

  • GI(Mvt type 201) following a GI(Mvt type 101)

    Hi all, When i  do a goods receipt(Mvt type 101) via MIGO, I want  to launch a goods Issue(Mvt type 201) just after,  like print individual slip. I tested special function in the output type but it not works Please suggest any idea... Thanks and Rega

  • Tracking and maintaining data about modifications done to Standard SAP code

    Hi All, I need your help to know if there is a way to track and maintain the modification changes done to standard SAP code. I have gone through SE95 but not much help. Is there any DB tables which stores these information after a standard SAP code h