HOW CAN I   WRITE   TEXT IN A     FILE

HI,
I have problems with saving files on my hard disk with an JAVA Applet.
Do you know how to do it in the best way?
here is the code i'm trying:
public String getCount()
      int count=456;
      String rec=null;
      DataOutputStream dos = null;
      try
        URL                url;
        URLConnection      urlConn;      
        url = new URL(getCodeBase().toString() + "counter.txt");
        urlConn = url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
        rec=""+count;
        dos = new DataOutputStream(urlConn.getOutputStream());
        dos.writeChars(rec);
        dos.flush();
        dos.close();
       catch (MalformedURLException mue) { return mue.toString(); }
       catch (IOException ioe) { return ioe.toString(); }
      return rec;
    }this code is simply saving the value ot count in the file "counter.txt"
I think the problem comes at the line: dos = new DataOutputStream(urlConn.getOutputStream());
It doesn't throws exception, it just stopes there and doesn't show any result.
WHY?
If you have some ideas ...thanks.
the class DataInputStream is working perfectly. I'm reading, but saving does not work.

You're using getCodeBase() to construct the file name, apparently, so I guess you are wanting to write to a file on the server where the applet was loaded from. And it looks like you're trying to do a POST to the URL that you construct, or something like that. But the URL ends in ".txt" so most likely your server isn't exposing that URL to the outside world.
You're on the right track, but you need to write to a URL that can accept POST requests and knows what to do with them. You can't just write to a file on the server -- if you could do that in your applet then anybody in the world could do it from a simple program, so consider the security implications of that.

Similar Messages

  • How can I write relative path in File, ImageIcon objects

    I have downloaded examples from
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/index.html
    but for some reason images are invisible until I write absolute paths?(I use windows) How can I write relative path in File, ImageIcon objects?

    Hello;
    I've found a lot of complaints about this through the Forte forum as well as on Dejanews. I'm just curious as to whether any of you ended up finding a solution to this problem.
    There was one posting about setting up the subdirectory as a URL rather than a String and then using that as the source of the ImageIcon ... but this didn't work for me.
    Any help whatsoever would be appreciated.
    Thanks!

  • How Can I write text in color

    Simple use for text output is System.out.println("Hallo");
    But how Can I write text in different color?

    http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

  • How can i write an image to file

    hi everybody,
    How can i write a java.awt.Image object to a file.I want to write it to file as a jpg image.Is ther any jpegencoder which can write an Image object to file.
    any tips or suggestions
    Thanks in advance

    This may be only of limited use but it shows an encoder in use.
    http://forum.java.sun.com//thread.jsp?forum=5&thread=140954
    http://forum.java.sun.com/thread.jsp?forum=48&thread=446603&tstart=0&trange=15
    rykk

  • How can I write text in front of attachments?

    I want to send five PDFs by email. When I highlight and click email, the attachments appear in the message body.  I want to write text before these attachments but I can't seem to be able to move the cursor in front of the first picture. Does anyone know how I can do this? Or send the attachments as thumbnails?

    Hello Biojem,
    This can be done by right-clicking the PDFs as they appear in Mail, then choosing "View as Icon."
    To change the way the PDF file is displayed in the current message window, Control-click the icon or visible portion of the PDF and choose "View in Place" or "View as Icon" as appropriate from the shortcut menu. Note that this only affects how you see the PDF in this message's window, it is not a permanent change.
    Mac OS X Mail: About PDF attachments
    http://support.apple.com/kb/TA22343
    Cheers,
    Allen

  • How can i write also to xml file the settings of the Tag property to identify if it's "file" or "directory" ?

    The first thing i'm doing is to get from my ftp server all the ftp content information and i tag it so i can identify later if it's a file or a directory:
    private int total_dirs;
    private int searched_until_now_dirs;
    private int max_percentage;
    private TreeNode directories_real_time;
    private string SummaryText;
    private TreeNode CreateDirectoryNode(string path, string name , int recursive_levl )
    var directoryNode = new TreeNode(name);
    var directoryListing = GetDirectoryListing(path);
    var directories = directoryListing.Where(d => d.IsDirectory);
    var files = directoryListing.Where(d => !d.IsDirectory);
    total_dirs += directories.Count<FTPListDetail>();
    searched_until_now_dirs++;
    int percentage = 0;
    foreach (var dir in directories)
    directoryNode.Nodes.Add(CreateDirectoryNode(dir.FullPath, dir.Name, recursive_levl+1));
    if (recursive_levl == 1)
    TreeNode temp_tn = (TreeNode)directoryNode.Clone();
    this.BeginInvoke(new MethodInvoker( delegate
    UpdateList(temp_tn);
    percentage = (searched_until_now_dirs * 100) / total_dirs;
    if (percentage > max_percentage)
    SummaryText = String.Format("Searched dirs {0} / Total dirs {1}", searched_until_now_dirs, total_dirs);
    max_percentage = percentage;
    backgroundWorker1.ReportProgress(percentage, SummaryText);
    percentage = (searched_until_now_dirs * 100) / total_dirs;
    if (percentage > max_percentage)
    SummaryText = String.Format("Searched dirs {0} / Total dirs {1}", searched_until_now_dirs, total_dirs);
    max_percentage = percentage;
    backgroundWorker1.ReportProgress(percentage, SummaryText);
    foreach (var file in files)
    TreeNode file_tree_node = new TreeNode(file.Name);
    file_tree_node.Tag = "file";
    directoryNode.Nodes.Add(file_tree_node);
    numberOfFiles.Add(file.FullPath);
    return directoryNode;
    The line i'm using to Tag is:
    file_tree_node.Tag = "file";
    So i know what is "file" then i make a simple check if the Tag is not null then i know it's a "file" if it's null then it's directory.
    For example this is how i'm checking if it's file or directory after getting all the content from my ftp server:
    if (treeViewMS1.SelectedNode.Tag != null)
    string s = (string)treeViewMS1.SelectedNode.Tag;
    if (s == "file")
    file = false;
    DeleteFile(treeViewMS1.SelectedNode.FullPath, file);
    else
    RemoveDirectoriesRecursive(treeViewMS1.SelectedNode, treeViewMS1.SelectedNode.FullPath);
    I also update in real time when getting the content of the ftp server xml file on my hard disk with the treeView structure information so when i'm running the program each time it will load the treeView structure with all directories and files.
    This is the class of the xml file:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Windows.Forms;
    namespace FTP_ProgressBar
    class TreeViewXmlPopulation
    // Xml tag for node, e.g. 'node' in case of <node></node>
    private const string XmlNodeTag = "node";
    // Xml attributes for node e.g. <node text="Asia" tag=""
    // imageindex="1"></node>
    private const string XmlNodeTextAtt = "text";
    private const string XmlNodeTagAtt = "tag";
    private const string XmlNodeImageIndexAtt = "imageindex";
    public static void DeserializeTreeView(TreeView treeView, string fileName)
    XmlTextReader reader = null;
    try
    // disabling re-drawing of treeview till all nodes are added
    treeView.BeginUpdate();
    reader = new XmlTextReader(fileName);
    TreeNode parentNode = null;
    while (reader.Read())
    if (reader.NodeType == XmlNodeType.Element)
    if (reader.Name == XmlNodeTag)
    TreeNode newNode = new TreeNode();
    bool isEmptyElement = reader.IsEmptyElement;
    // loading node attributes
    int attributeCount = reader.AttributeCount;
    if (attributeCount > 0)
    for (int i = 0; i < attributeCount; i++)
    reader.MoveToAttribute(i);
    SetAttributeValue(newNode,
    reader.Name, reader.Value);
    // add new node to Parent Node or TreeView
    if (parentNode != null)
    parentNode.Nodes.Add(newNode);
    else
    treeView.Nodes.Add(newNode);
    // making current node 'ParentNode' if its not empty
    if (!isEmptyElement)
    parentNode = newNode;
    // moving up to in TreeView if end tag is encountered
    else if (reader.NodeType == XmlNodeType.EndElement)
    if (reader.Name == XmlNodeTag)
    parentNode = parentNode.Parent;
    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
    //Ignore Xml Declaration
    else if (reader.NodeType == XmlNodeType.None)
    return;
    else if (reader.NodeType == XmlNodeType.Text)
    parentNode.Nodes.Add(reader.Value);
    finally
    // enabling redrawing of treeview after all nodes are added
    treeView.EndUpdate();
    reader.Close();
    /// <span class="code-SummaryComment"><summary>
    /// Used by Deserialize method for setting properties of
    /// TreeNode from xml node attributes
    /// <span class="code-SummaryComment"></summary>
    private static void SetAttributeValue(TreeNode node,
    string propertyName, string value)
    if (propertyName == XmlNodeTextAtt)
    node.Text = value;
    else if (propertyName == XmlNodeImageIndexAtt)
    node.ImageIndex = int.Parse(value);
    else if (propertyName == XmlNodeTagAtt)
    node.Tag = value;
    public static void SerializeTreeView(TreeView treeView, string fileName)
    XmlTextWriter textWriter = new XmlTextWriter(fileName,
    System.Text.Encoding.ASCII);
    // writing the xml declaration tag
    textWriter.WriteStartDocument();
    //textWriter.WriteRaw("\r\n");
    // writing the main tag that encloses all node tags
    textWriter.WriteStartElement("TreeView");
    // save the nodes, recursive method
    SaveNodes(treeView.Nodes, textWriter);
    textWriter.WriteEndElement();
    textWriter.Close();
    private static void SaveNodes(TreeNodeCollection nodesCollection,
    XmlTextWriter textWriter)
    for (int i = 0; i < nodesCollection.Count; i++)
    TreeNode node = nodesCollection[i];
    textWriter.WriteStartElement(XmlNodeTag);
    textWriter.WriteAttributeString(XmlNodeTextAtt,
    node.Text);
    textWriter.WriteAttributeString(
    XmlNodeImageIndexAtt, node.ImageIndex.ToString());
    if (node.Tag != null)
    textWriter.WriteAttributeString(XmlNodeTagAtt,
    node.Tag.ToString());
    // add other node properties to serialize here
    if (node.Nodes.Count > 0)
    SaveNodes(node.Nodes, textWriter);
    textWriter.WriteEndElement();
    And this is how i'm using the class this method i'm calling it inside the CreateDirectoryNode and i'm updating the treeView in real time when getting the ftp content from the server i build the treeView structure in real time.
    DateTime last_update;
    private void UpdateList(TreeNode tn_rt)
    TimeSpan ts = DateTime.Now - last_update;
    if (ts.TotalMilliseconds > 200)
    last_update = DateTime.Now;
    treeViewMS1.BeginUpdate();
    treeViewMS1.Nodes.Clear();
    treeViewMS1.Nodes.Add(tn_rt);
    TreeViewXmlPopulation.SerializeTreeView(treeViewMS1, @"c:\XmlFile\Original.xml");
    ExpandToLevel(treeViewMS1.Nodes, 1);
    treeViewMS1.EndUpdate();
    And when i'm running the program again in the constructor i'm doing:
    if (File.Exists(@"c:\XmlFile\Original.xml"))
    TreeViewXmlPopulation.DeserializeTreeView(treeViewMS1, @"c:\XmlFile\Original.xml");
    My question is how can i update the xml file in real time like i'm doing now but also with the Tag property so next time i will run the program and will not get the content from the ftp i will know in the treeView what is file and what is directory.
    The problem is that now if i will run the program the Tag property is null. I must get the ftp content from the server each time.
    But i want that withoutout getting the ftp content from server to Tag each file as file in the treeView structure.
    So what i need is somehow where i;m Tagging "file" or maybe when updating the treeView also to add something to the xml file so when i will run the progrma again and read back the xml file it will also Tag the files in the treeView.

    Hi
    Chocolade1972,
    Your case related to Winform Data Controls, So i will move your thread to Windows Forms> Windows
    Forms Data Controls and Databinding  forum for better support.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How can I write more than 32k file in oracle directory

    Hi experts,
    I am struggling while I write more than 32k file size in oracle directory, and throws an error ‘ORA-06502: PL/SQL: numeric or value error, like this.
    This is my procedure
    declare
    l_s_filename   UTL_FILE.file_type;
    begin
       l_s_filename := UTL_FILE.fopen ('INFO_MIGRATION', 'finfinne.txt', 'W');
    FOR rec
          IN ( SELECT SQL_REDO
                  FROM V$LOGMNR_CONTENTS
                 WHERE seg_owner <> 'SYS' AND username = 'GENTEST'
                 AND TABLE_NAME NOT LIKE '%_TEMP'
                       AND OPERATION IN ('UPDATE','INSERT','DELETE')
              ORDER BY TIMESTAMP)
       LOOP
          UTL_FILE.put_line (l_s_filename, rec.SQL_REDO);
       END LOOP;
       UTL_FILE.fclose (l_s_filename);
    end;can any please help me how can I overcome this problem
    Thanks,
    Arun

    You can write by breaking it into small chunks. Also you can try to use DBMS_XSLPROCESSOR.CLOB2FILE. For UTL_FILE the code snippets may looks like
    -- Read chunks of the CLOB and write them to the file
    -- until complete.
       WHILE l_pos < l_blob_len
       LOOP
          DBMS_LOB.READ (rec.l_clob, l_amount, l_pos, l_buffer);
          UTL_FILE.put_line (l_file, l_buffer, FALSE);
          l_pos := l_pos + l_amount;
       END LOOP;

  • How can I hide text on pdf file?

    I have a few invoices that I need to hide/blur the values. How can I do that?
    Thank you in advance.

    There is not much you can do with Adobe Reader, except perhaps using the free form pen under markups, to erase some text.
    With Acrobat you could delete some text portions.  But to blur I guess you would need something like Photoshop.

  • How can you write TABs in a file?

    Hello everbody,
    suppose you create a simple textfile "Input.txt" in copying the following two lines:
    ABCD
    123
    The code below works fine in creating (on Windows) an ANSI file "Output.txt". Now
    remove the comment slashes in the while loop, and compile and run the program
    again. The output file this time will be a Unicode file with Devanagari
    characters, as two bytes are interpreted as one char. Can anybody tell me why,
    and how it can be prevented?
    import java.io.*;
    class Anwendung
      public static void main(String[] args)
    //    final byte TAB=9; // no difference.
        final int TAB=9;
        try
        { FileInputStream eingabe = new FileInputStream("Input.TXT");
          FileOutputStream ausgabe = new FileOutputStream("Output.TXT");
          int zeichen;
          while ((zeichen=eingabe.read()) != -1)
          { ausgabe.write(zeichen); // only the low byte is taken from the int.
         ausgabe.write(TAB);
          eingabe.close();
          ausgabe.close();
        catch(Throwable e)
        { System.out.println("Error: "+e);
    }Regards
    Joerg

    Hello Tim,
    thanks for your response. Meanwhile I found out, that in fact things work fine. I "tested" the outputfile in opening it with the Notepad editor. That was not the proper way to do it. Making a file dump, I saw that everything was alright. So if one wants to work on such a file with the editor, one should use the Writer classes.
    Regards
    Joerg

  • How can I write to a (external)file from a stored procedure

    I want to write some data to a (external) file. I have it working with the function UTL_FILE.
    My problem is I want to write to a file on a mapped drive (so a drive on a different machine). This is not working.
    Does anyone know a way to build this.
    Please send your responses to [email protected]
    Many thanks,
    Alex Nagtegaal

    an extraction out of expert one-on-one from Thomas Kyte
    <quote>
    when an oracle istance is created the services that support it are setup to 'log on as' the system (or operating system) account, this account has very few privileges and no acces to Window NT Domains. To access another Windows NT machine the OracleServiceXXXX must be setup to logon to the appropriate Windows NT Domain as a user who has acces to the required location for UTL_FILE.
    To change the default logon for the Oracle services go to (in Windows NT):
    Control Panel | Services | OracleServiceXXXX | startup | log on as; (where XXXX is the instance name)
    In Windows 2000, this would be:
    Control Panel | Administrative Tools | Services | OracleServiceXXX | Properties | Log on tab; (again XXXX is the instance name)
    Choose the This Account radio button, and then complete the appropriate domain login information. ONce the services have been setup as a user with the appropriate privileges, ther are two options dfor setting UTL_FILE_DIR:
    * Mapped Dirve: To use a mapped drive, the user that the service starts as must have setup a drive to match UTL_FILE_DIR and be logged onto the server when UTL_FILE is in use.
    * Universal Naming Convention: UNC is preferable to Mapped Drives because it does not require anyone to be logged on and utl_file_dir should be set to a name in the form \\<machine name>\<share name>\<path>
    You will of course need to stop and restart Oracle after changing the properties of the service.
    <\quote>
    I want to write some data to a (external) file. I have it working with the function UTL_FILE.
    My problem is I want to write to a file on a mapped drive (so a drive on a different machine). This is not working.
    Does anyone know a way to build this.
    Please send your responses to [email protected]
    Many thanks,
    Alex Nagtegaal

  • How can I copy text from pdf file to Pages or Word?

    I recently changed to Lion. When I try to copy pdf text from either Preview or Adobe reader into either Pages or Microsoft Word I get all undecipherable characters. This did not happen in previous OSX versions. Is there a fix?

    I have found that some pdf's are "protected" so that it is not possible to copy text. Does this happen to all your pdfs, or just some?
    If it is just some of the pdfs, then this might help:
    http://hints.macworld.com/article.php?story=20040622214927503
    charlie

  • How can i write info in text filefrom servlet

    hello
    can u give me exmaple how can i write data into text file from servlet ?
    Edited by: bla123456789654 on May 17, 2010 2:05 PM

    javax.servlet.GenericServlet
    public void log(java.lang.String msg)
    Writes the specified message to a servlet log file, prepended by the servlet's name.
    See ServletContext.log(String).
    Parameters:
            msg - a String specifying the message to be written to the log file
    */

  • How can I Write a sine wave in an Access-fil​e?

    I measure a sine wave in LabView 6i. How can I write the datas automatically to an Acces-file, at the same time?
    In my program, I managed it with Execute SQL.vi, I change a number in a SQL statement(String) -> after this I push start and then it writes the statement in the Access-file.
    The problem is, it writes only one data per measurement in the file. How can I write all datas in the Access-file and measure the wave at the same time?
    Thanks for help!
    Attachments:
    getwave.vi ‏49 KB

    On the waveform palette, you will find a "to components" vi that you can break out the array of the waveform. You can then, using a for loop write all of the values from the waveform.
    Better yet, there are examples in the database toolkit manual on pages 3-13 to 3-15 that deal with reading arrays (and even has a waveform example).
    Good luck!

  • I write digital port by 'DAQmx Configure Logging.vi​' and receive TDMS file with 8 boolean channels. How can I write to 1 integer channel?

    Hello!
    I want to write 1 digital port from PXI-6536 with streaming to TDMS file.
    I'm writing by 'DAQmx Configure Logging.vi' and become TDMS file with 8 boolean channels.
    How can I write to 1integer channel?
    Attachments:
    1.JPG ‏27 KB

    Hey Atrina,
    The actual data stored on disk is just the raw data (that is, a byte per sample in your case).  It's really just a matter of how that data is being represented in LabVIEW whenever you read back the TDMS file.
    I'm not sure if there is a better way to do this, but here is a way to accomplish what you're wanting:
    Read back the TDMS file as a digital waveform.  Then there's a conversion function in LabVIEW called DWDT Digital to Binary.  This function will convert that set of digital channels into the "port format" that you're wanting.  I've attached an example of what I mean.
    Note: When looking at this VI, there are a few things that the downgrade process did to the VI that I would not recommend for these TDMS files.  It added a 1.0 constant on the TDMS Open function, and it set "disable buffering" on the TDMS Open function to false; you can get rid of both of those constants.
    Message Edited by AndrewMc on 01-27-2010 11:21 AM
    Thanks,
    Andy McRorie
    NI R&D
    Attachments:
    digitalconvert.vi ‏13 KB

  • How can I read text files from LAN if I only know the hostname?

    I'm new in Java Developing, and dont know the written classes yet. I need help, how to do the following steps?
    <p>1. How can I read text files from LAN if I only know the hostname, or IP address?
    <p>2. How to read lines from text files without read all lines from the beginning of file, just seek to a position.
    (ex. how can I read the 120th line?)
    <p>Please help!
    <p>sorry for the bad english

    I'm new in Java Developing, and dont know the written classes yet. I need help, how to do the following steps?
    1. How can I read text files from LAN if I only know the hostname, or IP address?You need to know the URL of the file. You need to know the hostname, port, protocl and relative path.
    The hostname is server, not file.
    2. How to read lines from text files without read all lines from the beginning of file, just seek to a position.Use the seek() to get to a random byte.
    (ex. how can I read the 120th line?)The only way to find the 120th line is to read the first 120 lines. You can use other file formats to find the 120th line without reading the whole file but to need to be able to detremine where the 120th line is

Maybe you are looking for

  • My sister's iPod isn't being read by iTunes.

    My sister just got a new iPod Classic. We hooked it up to the family computer and Windows found it, but iTunes won't read it. We tried it on my computer and it worked fine. After updating iTunes and following the guide on this site, it still won't wo

  • Iphone for ipod touch?

    is it possible to trade in an 8gb ipod touch 4 gen for an iphone 4s?

  • Connect a PC to My existing Wireless Network Using Airport Extreme

    this is my issue i bought a Airport Express to connect a PC via ethernet to my wireless network already working at home. Cant figure out the settings???? need help. My home network is using a airport extreme base station. the problem is the PC doesn'

  • BPM activation error

    Hello experts, i have a this scenario where i get a status change request from an exteral system, based on certain validations i change the status and send the response back. i created these Msg types and Msg interfaces and activated them: StatusChan

  • A media driver your computer needs is missing

    I have been trying reinstall my windows 64 bits, but I always get the message a media driver your computer needs is missing. I have tried to install different isos, tried to boot from dvd and usb and i also tried to download all drivers and put all t