How to write file

The first file is a .dat file(located at C:/Program Files/Client) I am able to read this, but I need to make it look like the 2nd file(which won't exist yet)and save it in a different location. ex C:/program Files/Microsoft/
and saved as something.ctt
//1st file (first.last.dat)
Version=3.1.3
G 289f9;80256d8c/Administrators3 Administrators O
G My;Group2 My;Group O
U william.flentje1:: william.flentje,bill.flentje
U bryan.miller1:: bryan.miller
U david.kratzer1:: david.kratzer,
U greg.mcbroom1:: greg.mcbroom,
G Test2 Test O
U kevin.leahy1:: kevin.leahy,
U marcia.lemon1:: marcia.lemon,
//2nd file to be created (first.last.ctt)
<?xml version="1.0"?>
<messenger>
<service name="Microsoft">
<contactlist>
<contact>[email protected]</contact>
<contact>[email protected]</contact>
<contact>[email protected]</contact>
<contact>[email protected]</contact>
<contact>[email protected]</contact>
<contact>[email protected]</contact>
</contactlist>
</service>
</messenger>
Below is the code I have so far.
Thank you for any help in advance
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
//import javax.swing.filechooser.FileFilter;
public class Sametime extends JFrame implements ActionListener {
     JPanel panel = new JPanel();
     JTextArea jta =
          new JTextArea(
     //Instructions for user     
               "There are a few steps that must be taken.\n"
                    + "1. Save your current List to your PC.\n    "
                    + "The default location should be: C:/Program Files/Client.\n"
                    + "2. Open the Client.\n"
                    + "3. Click on People\n"
                    + "4. Click on Save List.\n"
                    + "5. Save as your first.last.dat");
     JButton browse = new JButton("Continue");
     JButton exit = new JButton("Exit");
     public Sametime() {
          super("List Migration");
          setSize(550, 200);
          Container c = this.getContentPane();
          c.add(panel);
          browse.addActionListener(this);
          exit.addActionListener(this);
          panel.add(jta);
          panel.add(browse);
          panel.add(exit);
          jta.setEditable(false);
          setLookAndFeel();
          setVisible(true);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     } //end Sametime         
     public void actionPerformed(ActionEvent e) {
          //Location for JFileChooser default location          
          JFileChooser fc = new JFileChooser("/Program Files/Client");
          if (e.getSource() == browse) {
               int returnVal = fc.showOpenDialog(Sametime.this);
               if (returnVal == JFileChooser.APPROVE_OPTION) {
                    try {
                         StringBuffer text = new StringBuffer();// stingbuffer to hold the file text      
                         String line;// temp varial to hold a line of text from the file      
                         BufferedReader in =
                              new BufferedReader(
                                   new FileReader(fc.getSelectedFile()));
                         while ((line = in.readLine()) != null) {
                              text.append(line).append("\n");
                         in.close();
                         String textFile = text.toString();//do something with the text file text
                         System.out.println(textFile); 
                    } catch (IOException ioe) {}
                    //System.exit(0); 
               } //end if          
               if (e.getSource() == exit) {
                    System.exit(0);
               } //end if     
          } //end actionPerformed         
          public static void main(String[] args) {
               Sametime st = new Sametime();
          } //end main
          //setLookAndFeel       
          private void setLookAndFeel() {
               try {
                    UIManager.setLookAndFeel(
                         UIManager.getSystemLookAndFeelClassName());
                    SwingUtilities.updateComponentTreeUI(this);
               } catch (Exception e) {
                    System.err.println("Could not use Look and Feel:" + e);
               } //end catch     
          } //end void setLookAndFeel
     } //end public class Sametime

Try this:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class Sametime extends JFrame implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        //Location for JFileChooser default location       
        JFileChooser fc = new JFileChooser("/Program Files/Client");
        if (e.getSource() == browse) {
            int returnVal = fc.showOpenDialog(Sametime.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    String[] contactArray = parseDatFile(fc.getSelectedFile());
                    Document document = createXMLDocument(contactArray);
                    saveToXMLFile(document, new File("C:/program Files/Microsoft/", "first.last.ctt"));
                } catch (Exception exc) {
                    exc.printStackTrace();
                //System.exit(0); 
        } //end if     
        if (e.getSource() == exit) {
            System.exit(0);
        } //end if 
    } //end actionPerformed    
    String[] parseDatFile(File datFile) throws Exception {
        List list = new ArrayList();
        BufferedReader br = new BufferedReader(new FileReader(datFile));
        String line;
        while ((line = br.readLine()) != null) {
            line = line.trim();
            if (line.indexOf("U") != 0)
                continue;
            int p0 = line.indexOf("::");
            if (p0 == -1)
                continue;
            int p1 = line.indexOf(",", p0 + 2);
            if (p1 != -1)
                line = line.substring(p0 + 2, p1);
            else
                line = line.substring(p0 + 2);
            line = line.trim() + "@d.com";
            if (list.indexOf(line) == -1)
                list.add(line);
        String[] contactArray = new String[list.size()];
        list.toArray(contactArray);
        return contactArray;
    Document createXMLDocument(String[] contactArray) throws Exception {
        DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dBF.newDocumentBuilder();
        DOMImplementation domImpl = builder.getDOMImplementation();
        Document document = domImpl.createDocument(null, "messenger", null);
        Element root = document.getDocumentElement();
        Element svcElm = document.createElement("service");
        Element clElm = document.createElement("contactlist");
        svcElm.setAttribute("name", "Microsoft");
        svcElm.appendChild(clElm);
        root.appendChild(svcElm);
        for (int i = 0; i < contactArray.length; i++) {
            Element conElm = document.createElement("contact");
            Text conTxt = document.createTextNode(contactArray);
conElm.appendChild(conTxt);
clElm.appendChild(conElm);
return document;
void saveToXMLFile(Document document, File xmlFile) throws Exception {
OutputStream os = new BufferedOutputStream(new FileOutputStream(xmlFile));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
} //end public class Sametime

Similar Messages

  • How to write file at server end?

    Hi,
    I use a af:inputFile component to receive uploaded files. And want to write files to the directory of server. However, when execute java.io.File.createNewFile(), it throw exception. How to resolve it?
    import org.apache.myfaces.trinidad.model.UploadedFile;
    import javax.faces.event.ValueChangeEvent;
    import java.io.InputStream;
    import java.io.File;
    public class UploadFileHandler {
        public void doUpload(ValueChangeEvent event) throws IOException {
            File file = new File("C:\temp.txt");
            *file.createNewFile();* //Error happen here.
    }

    Hi Cheney,
    It is good practice to use System.getProperty("file.separator") instead of hardcoding "/" or "\" .
    Though your issue is resolved by using "//", you might want to consider changing to the above.
    -Arun

  • How to write file to server side?

    hello,
    Could anyone pls help me...
    I just want to see an example how can I write to a file that is placed at the server(save place as the applet).
    p.s. I have been successfully read a file from there...
    Suppose I have signed the applet (self-signed), anymore security problem I need to pay attention to?
    Thanks a lot!!

    hi mandy, from the applet u can send the file to be written into the server to a servlet running in server and the servlet can in turn write the file into the servlet. by applet - servlet communication, u can easily read and write files to the server.

  • How to write files to the filesystem with portal/plsql

    Hi,
    is there a way to write files to the filesystem via Portal?
    Or can i call an external programm (perl, php) to do so, while portal writes further information to database?
    thank you for the help
    Ralf Schmitt

    Hi Ralf,
    my primary task is to publish download-links to files stored ... somewhere as a linklist. I tried to store and download files to/from the database but i cant get it to run. Upload works, download doesn't.
    (i'm not talking about a single form-query-download-link! I need a report-like linklist)If you want to do this you'll have to write some code but sure it's possible - i did it myself.
    The links in the link list in your report should call a stored function retrieving the files from Wwdoc_document or whatever is the document table defined in your DAD. Simply select BLOB_CONTENT into a BLOB variable from the table, provided you know what file to read :-) The function would then read the BLOBs and send them to the client's browser via DBMS_LOB - it's poor design but it works just as smooth as it could and it's really performing. This would simply display the file into your browser or prompt for file save location, depending on what browser you are using and its client settings.
    I guess this is not so clear, if you want some more details feel free to e-mail me at [email protected]
    Another way would be to use wpg_docload to both download and upload files to/from the DB.
    Now i try to figure out if it is possible to store the files to the filesystem and write only additional info like description or path into db.Again, yes, it is. I can't recall exactly how I did it ^_^ but the trick is to create a virtual directory in the DB - pointing at a physical directory on the file system you want to write to, and you have to have full read-write permission on the directory itself, and its path must be included in the utl_file_dir database parameter. Then you use both COM Automation or UTL_FILE to write files.
    would it be possible to let a portal-form write info to the db and then pass the file to a php-script?
    regards,
    Ralf Schmitt

  • How to write files to phweb share drive(phweb is nonsap system)

    Hi all,
             Is there any way to write files directly to phweb share drive(phweb is Nonsap system).
    Thanks,
    Balalji

    Hi Rob,
               Yaa I got .But how to use that function modules and when to use.I heard that first we have to write to presenation server and then we can use one of those function modules.Is it right?
    Thanks,
    Balaji

  • How to  write file excel format xlsx/xlsb to pl/sql?

    Dear supporter,
    I built the xml report output excel file. However, the reported data and about 30 columns, line 200000 write and loading file slow, large file size
    How can write data directly to the format xlsb / xlsx from pl / sql. quickly and efficiently.
    Please, help me!
    Tks,
    Mr.T

    Check this thread.
    Re: 5. How do I read or write an Excel file?

  • How to write files on Client Machine using JSP

    Hi,
    I am new to JSP. Please tell me how do i write files on Client machine thru a Browser.
    Please let me know at the Earliest.
    Thanks.
    Mehul Dave

    1) Well I find it rather convenient to deploy a web app as just one file rather than a bunch of files. For deployment it's much better. However I prefer using expanded files when developping (to use auto reload in Tomcat for example)
    2) It is a bad idea to upload files inside your webapp's context (ie: in it's deployment directory) because one day an uninformed system administrator might come and redeploy the web app and therefore delete all your uploaded files (believe me, I've already experienced this!)
    What i do usually is upload it in a completely different directory, something like /uploaded_files. Your uploaded files are therefore completely independant from your webapp
    However it is a bit trickyer to get those files back. Let's take the example of image uploads. You have 2 ways of proceeding:
    - the easiest : configure your web server (apache etc...) to redirect a certain url to your external directory. For example the /upload url will point to a /uploaded_files directory. This is easier to do and the fastest way to serve images but not always the best solution: you are dependant on the web server's configuration and you can't control the visibility on your files (no security constraints, anyone can see your uploaded files if they know the url).
    - you can also write a servlet which will load the file as an array of bytes and send it back in the response.
    You can call it this way :
    <img src="/serlvets/showmyimage?path=uploaded.gif">
    in this way you can control your uploaded files better: you may want to define security constraints on the visibity or not of uploaded files depending on the user which has logged on the site.

  • How to write file in Applet

    I have a code:
    URL url = new URL("http://hostname/file.txt");
    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    OutputStream out = con.getOutputStream();
    String s = "Test";
    byte[] b = s.getBytes();
    out.write(b);
    out.close();
    But it does not create or save into file.
    Please tell me how to solve it.
    Thanks.
    Nghianh

    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

  • How  applet write file in local system by URL instead of FileOutputStream()

    hi,
    how can applet write a file in local system through URL instead of FileOupStream()
    plz.....plz.....plz......
    URL url = new URL(" file://c:/temp.txt");
    in this url how applet can write
    plz....

    URL uses http to cummunicate, this means you can send and receive data using the http
    protocol.
    The OS doesn't do anything with this, you need a http server to interpret these messages
    and take appropriate action (with server side script or CGI).
    So if the client has a http server installed and has server side script thad does
    something with your http request (that's what a url does) than it is possible.
    Since both having a http server , server side script and or CGI have nothing to do with
    signed applets I will not answer your question here.
    But the mail reason I won't answer it is because it makes no sence to use a URL to write
    to the local file system.

  • How creat flle and and how to write file network

    eg:\\bissstorage\Backups\sudhir
     i want to write inside ths folder...how to get path
    i tried this one 
    iFile = OpenFile ("\\bissstorage\\Backups\\sudhir\\TransducersDetails\\TransducersDetails.txt" , VAL_READ_WRITE, VAL_APPEND, VAL_ASCII); 
    but its not working im using cvi 5.5
    thank you
    Sudhir

    In a network pathname, some backslashes are doubled due to UNC naming rules: you must reflect this in your string, considering that each backslash character must be doubled to be used as is and not as an escape marking; that is, this string should work:
    iFile = OpenFile ("\\\\bissstorage\\Backups\\sudhir\\TransducersDetails\\TransducersDetails.txt" , VAL_READ_WRITE, VAL_APPEND, VAL_ASCII); 
    The same applies in case you want to build up the path with MakePathname: in this case you should do the following:
    char    file[512];
    MakePathname ("\\\\bissstorage", "Backups", file);
    MakePathname (file, "sudhir", file);
    MakePathname (file, "TransducersDetails", file);
    MakePathname (file, "TransducersDetails.txt" , file); 
    iFile = OpenFile (file , VAL_READ_WRITE, VAL_APPEND, VAL_ASCII); 
     

  • How to write file into multiple directories by using file adapter?

    i need to write my file into multiple directories,i able to do in single directory.But i need to write to muliple directories.Please help me out.Thanks in advance.

    If you are passing the values at runtime then you can loop it and and invoke the file adapter in loop by dynamically passing the value in invoke properties for "File Directory and File name" etc.

  • How to write file in user's local desktop

    Hi,
    Using the WriteFile action, i can write the file in inetpub/wwwroot in server.
    Is there any way to write the file in user's local drive folder?
    Although now i am writing the file to server and allowing the user to access it through URL but I suspect that there could be user concurrent issue or file contamination issue.
    Constraint - The file should open with the default name.
    If i try to open a local copy to the user (thru SaveasCSV() or URL)  and allow the user to save the copy then the default name appear as Illumniator.
    Regards,
    Anil

    I think your current approach of saving to the web location and providing the user access via URL is the best approach.  From a security standpoint I can't see that writing directly to a user's desktop/laptop would be a good idea.
    If you are worried about naming or concurrency issues, then create sub folders that match their user name, or devise a naming convention that allows the objects to be unique between users and purpose.

  • How to write file to server using applet?

    Please help!!!!!!!!!!
    Why didn't this work?
    URLConnection ucon = url.openConnection();
                   ucon.connect();
                   ObjectOutputStream outStream = new ObjectOutputStream(new BufferedOutputStream(ucon.getOutputStream()));
                   outStream.writeObject(linkHolder);
                   outStream.close();
    .............As my applet run, the message printed out with my catch is: "java.net.UnknownSerivceException: Protocal doesn't support this output."
    However, the reading from server is fine:
    ObjectInputStream inStream = new ObjectInputStream(new BufferedInputStream(url.openStream()));
             links = (LinkHolder)inStream.readObject();
             inStream.close();
    ....I really appreciate for your help.
    JTom

    This file resides on server not local machine. I'm just testing on my local PC for now.
    By the way, applet doesn't allow any kind of communication to client machine or others, but only to the server it resides in; according to the specs.
    To get a url connection you need a server. You send
    the output to the server(some servlet or similar
    program running on server).
    But for file you don't need a server. You can open a
    file on your local machine if just have file
    permissions. There is no server involved here.

  • Can't write files!!!

    I need some code or a clear tutorial that explains how to write files using an applet. i want to create a game that you can save on so i want to save it to the server. can anyone help?
    thnx

    that site doesn't fully explain how to write files to
    a database from an applet. can u give something else.Well, it does answer some questions as to why you can't write files from an applet and I thought it would give you a better understanding of it and you could narrow your search into finding an answer. I guess I was wrong.
    Good luck though.

  • How to write Header and Footer elements in Write file Adapter

    Hi,
    I have a requirement to write the file.The write file contains header and footer elements ,how we can write these elements. These elements are fixed for all files.these are not come from any input.below is the sample file.
    $begintable
    name,Id,Desg
    ad,12,it
    $endtable

    Hi,
    I have created the XSD for you, and i created a sample SOA Composite which writes the file same like what you want, the below XSD can write a file with one header record, multiple data records and one trailer record.
    <?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"
    xmlns:tns="http://TargetNamespace.com/WriteFile"
    targetNamespace="http://TargetNamespace.com/WriteFile"
    elementFormDefault="qualified" attributeFormDefault="unqualified"
    nxsd:version="NXSD" nxsd:stream="chars" nxsd:encoding="UTF-8">
    <xsd:element name="Root-Element">
    <xsd:complexType>
    <!--xsd:choice minOccurs="1" maxOccurs="unbounded" nxsd:choiceCondition="terminated" nxsd:terminatedBy=","-->
    <xsd:sequence>
    <xsd:element name="RECORD1">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="header" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy="${eol}"
    nxsd:quotedBy='"'/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="RECORD2" minOccurs="1" maxOccurs="unbounded">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="data1" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy=","
    nxsd:quotedBy='"'/>
    <xsd:element name="data2" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy=","
    nxsd:quotedBy='"'/>
    <xsd:element name="data3" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy="${eol}"
    nxsd:quotedBy='"'/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="RECORD4" nxsd:conditionValue="$endtable">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="trailer" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy="${eol}"
    nxsd:quotedBy='"'/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>
    Hope this helps,
    N

Maybe you are looking for