Solved

String to File. Is it possible?

Posted on 1998-01-27
23
274 Views
Last Modified: 2012-06-21
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.
0
Comment
Question by:Deladier
  • 12
  • 4
  • 3
  • +3
23 Comments
 
LVL 16

Expert Comment

by:imladris
ID: 1232652
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.

0
 

Expert Comment

by:kristi
ID: 1232653
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.


0
 

Author Comment

by:Deladier
ID: 1232654
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.
0
 

Author Comment

by:Deladier
ID: 1232655
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.
0
 
LVL 16

Expert Comment

by:imladris
ID: 1232656
Sorry, better reject my answer. I know very little about ftp.

0
 

Author Comment

by:Deladier
ID: 1232657
Adjusted points to 75
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1232658
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.
0
 

Author Comment

by:Deladier
ID: 1232659
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.

0
 

Expert Comment

by:2clem
ID: 1232660
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.
0
 

Author Comment

by:Deladier
ID: 1232661
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.
0
 

Author Comment

by:Deladier
ID: 1232662
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.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Accepted Solution

by:
noahc earned 80 total points
ID: 1232663
Hi,

I am also known as 2clem (at home).  Since I fell the need to procrastinate, I will try to answer now.

When you call FTPClient.put(filename) you get back a TelnetOutputStream to which you can write the contents of your textArea.  You can do this as simply as attaching an OutputStreamWriter to your TelnetOutputStream and calling write() with the text from the TextArea as the parameter.  For Instance:

*Source to replace this line --> -----> s.put("filename.txt");

OutputStreamWriter ow = new     OutputStreamWriter(s.put("filename.txt"));
ow.write(textedi);

*end of source

And that's it.  Because I did not know this class, my previous assumption about what "put" did was incorrect; having a file on your system would not have done anything.  All this method does is give you a stream to which you can write.

HTH,

Noah
0
 

Author Comment

by:Deladier
ID: 1232664
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.
0
 

Expert Comment

by:2clem
ID: 1232665
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
0
 

Author Comment

by:Deladier
ID: 1232666
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.
0
 

Author Comment

by:Deladier
ID: 1232667
Note: ^ character was under ( character in previous comment.
0
 

Expert Comment

by:noahc
ID: 1232668
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
0
 

Expert Comment

by:noahc
ID: 1232669
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.
0
 

Author Comment

by:Deladier
ID: 1232670
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.
0
 

Expert Comment

by:2clem
ID: 1232671
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
0
 

Expert Comment

by:2clem
ID: 1232672
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
0
 

Author Comment

by:Deladier
ID: 1232673
Thanks for all your help Noah, I could finally write the file to server.
You help me a lot, Thanks again!.

  Deladier.
0
 

Author Comment

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

  Deladier.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now