Link to home
Start Free TrialLog in
Avatar of Deladier
Deladier

asked on

String to File. Is it possible?

Hi, I'd like to know if it's possible to convert a String and its contents to a File. Example:
String myName = "Sun in the sky"
to a File named myName(or another name) with contents:
"Sun in the sky"

It would be very useful for me. Could you please include some code.

     Thanks in advance.
Avatar of imladris
imladris
Flag of Canada image

Not directly no. But a small method would accomplish the result, for instance:

void stringToFile(String filename,String contents)
{    DataOutputStream do=new DataOutputStream(new                                                   FileOutputStream(filename));
     do.writeUTF(contents);
     do.close();
     return;
}

This would be the most portable and smallest option. You could also write out Java (doublebyte, i.e. Unicode) chars by converting the String to a char array (using String.toCharArray())
and then using do.writeChar()
or
you could convert the char array to bytes (with casts) and use writeByte, or the write method of the FileOutputStream directly and skip the DataOutputStream.

Avatar of kristi
kristi

Would this be what you are looking for?

String myName = "Sun in the sky";

BufferedWriter writer = new BufferedWriter(new FileWriter("someStringFileName"));
writer.write(myName, 0, myName.length());

Hope the info helps.


Avatar of Deladier

ASKER

The reason of the original question is:
I'm using FtpClient class for connecting to my account, and I already done it, and I can use FtpClient commands even put(String filename) command successfuly, but I'd like to put a file that I have modified in a TextArea "conten" of my Applet. I stored this TextArea contents in a String named "textedi".
I've tryed to write a file to server in many ways and only with FtpClient works fine, but I don't know how to adapt it to put command.
The following is the code for connection to server account, besides, creates an empty File named "filename.txt" in server account (using put):

    String textedi = conten.getText(); //value of modified text
       
        try      {
            FtpClient s;
            s = new FtpClient(valHost);
            s.openServer(valHost,21);
            state.appendText(s.getResponseString() +"\n");
            s.login(valLogin, valPassword);
            state.appendText(s.getResponseString() +"\n");
   ----->   s.put("filename.txt");
            state.appendText(s.getResponseString() +"\n");
            state.appendText("File saved.\n");
        } catch (Exception err) {
       state.appendText("Couldn't save file.\n");
       }

Abbreviating: Can I use put(String) command for to put a file that I have modified in a TextArea of my Applet ?.

   Thanks.
The reason of the original question is:
I'm using FtpClient class for connecting to my account, and I already done it, and I can use FtpClient commands even put(String filename) command successfuly, but I'd like to put a file that I have modified in a TextArea "conten" of my Applet. I stored this TextArea contents in a String named "textedi".
I've tryed to write a file to server in many ways and only with FtpClient works fine, but I don't know how to adapt it to put command.
The following is the code for connection to server account, besides, creates an empty File named "filename.txt" in server account (using put):

    String textedi = conten.getText(); //value of modified text
       
        try      {
            FtpClient s;
            s = new FtpClient(valHost);
            s.openServer(valHost,21);
            state.appendText(s.getResponseString() +"\n");
            s.login(valLogin, valPassword);
            state.appendText(s.getResponseString() +"\n");
   ----->   s.put("filename.txt");
            state.appendText(s.getResponseString() +"\n");
            state.appendText("File saved.\n");
        } catch (Exception err) {
       state.appendText("Couldn't save file.\n");
       }

Abbreviating: Can I use put(String) command for to put a file that I have modified in a TextArea of my Applet ?.

   Thanks.
Sorry, better reject my answer. I know very little about ftp.

Adjusted points to 75
Just a comment, Sandbox or no Sandbox, there are two files that you can always access from an apple, the keyboarad and your standard output device. You could try redirecting standard output to the keyboard, thus giving you a "normal" file to transfer via FTP.
Thanks JPK, as you see I have many troubles to write a file on server. Sorry, I hope not bother you with all my questions about the same stuff.
I understand why you are rated number 1 in top experts list.
  Thanks.

What is the interface for the FTPClient class that you mention?  Specifically, is there a method for "putting" a stream or text to the server, rather than just specifying a filename (which does the conversion of the file's contents to a stream for you)?  The problem is that right now, you don't have a file to send to the server.
Class sun.net.ftp.FtpClient info it's in:
   http://www.cdt.luth.se/java/doc/sun/shared/sun.net.ftp.FtpClient.html

and there is a put method: put(String filename)

You're right, I don't have a file to send (pre-existent), the modified file to put it's only in TextArea of my applet (non written yet), Do you think it's possible to use put method for write the changes made in TextArea to the file ?.

  Thanks.
Class sun.net.ftp.FtpClient info it's in:
                         http://www.cdt.luth.se/java/doc/sun/shared/sun.net.ftp.FtpClient.html

and there is a put method: put(String filename)

You're right, I don't have a file to send (pre-existent File), the modified file to put it's only in TextArea of my applet (File is not written yet), Do you think it's possible to use put method for write the changes made in TextArea to the file ?.


                        Thanks.

MESSAGE CORRECTED NOW.
ASKER CERTIFIED SOLUTION
Avatar of noahc
noahc

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, your answer seems reasonable but right now I'm using JDK 1.0.2, Can you adapt it to this Java version ?.

    Thanks again.
Sure,

TelnetOutputStream is inherited from BufferedOutputStream, so you could do (and it would probably be better anyway):

BufferedOutputStream buf = s.put("filename.txt");
buf.write(textedi.getBytes());

I've been thinking about it, though.  I suppose that you are using this undocumented (and unsupported) FTPClient class because you are using JDK 1.02?  Is the FTP protocol not supported in the URLConnection class in this version?  Or are there things that you can do that with this class that you can't with the URLConnection class?  Is this sun class in JDK 1.02?

You don't have to answer.  I suppose that if I were really curious, I could ask my own question for points:-)

Noah
I tryed the code but it had a mistake in compilation:
  No method matching getBytes() found in class java.lang.String
          buf.write(textedi.getBytes());
                                    ^  

Could you check it out please. Thanks.

P.S.: I found something about getBytes method of String class in:
http://zeus.fh-brandenburg.de/hotjava/doc/api/java.lang.String.html
and I think getBytes() form it's wrong, but verify it. Thanks.
Note: ^ character was under ( character in previous comment.
You are really going to make me work for this, aren't you?

Replace above with:

byte[] b = new byte[textedi.length()];
BufferedOutputStream buf = s.put("filename.txt"); buf.write(textedi.getBytes(0, textedi.length() - 1, b, 0));

The for I gave you was new in JDK 1.1.

Noah
Actually, it would probably be better if you wrapped your stream with a DataOutputStream, as imladris suggested, and use the writeChars method and pass the String into this method directly.
Sorry for the bothering, it wasn't my intention, OK?, I appreciate all your help, but I'm very pressed right now and it's clear that you are busy enough too. I'm not an expert in this and I ignore many tricks that are normal for you. I know something about Java programming but the the questions I ask in this forum are about unknown topics for me and I'd like to know it with more detail. Remember that you are the expert here, and if I knew the answers to my questions I wouldn't be here.
   
              Deladier.
Deladier,

I'm sorry, I didn't mean to sound snippish, it wasn't my intention to belittle you in any way.  I am in no way an expert, but I am happy to help you with anything I can.  That's how I learn too.

Were you clear about what's needed from my last post?

Noah
By the way an array is a collection of things of the same type that you can refer to and declare by the same name.  A book of mine adds that this group of things occupies a contiguous memory block.  A byte is a block of 8 bits and is often the smallest chunk of information fed to a computer (depending on the language).  So a byte array can be useful as a binary representation of data, as it is what the computer sees.

So when you feed a byte array to a stream, it is easy for the computer to accept it, as no translation (internally) is needed.

As to what you want to do, in the second post under noahc today, I mentioned that you don't have to convert to a byte array, but can instead do what imladris mentioned which looks like the following:

DataOutputStream ds = new
     DataOutputStream(s.put("filename.txt"));
ds.writeChars(textedi);


That should work.

Good luck,
Noah
Thanks for all your help Noah, I could finally write the file to server.
You help me a lot, Thanks again!.

  Deladier.
Thanks for all your help Noah, I could finally write the file to server.
Thanks again!.

  Deladier.