简体   繁体   中英

How to Write Data (String) to Text File

I currently have the lines of code:

ResultSet RS = cs.executeQuery();
....
FileOutputStream outFile = new FileOutputStream(file, false);
while(RS.next()) {
    outFile.write(RS.getString(1));
}

There is only one column in the resultset. I'm getting an error that RS.getString(1) must be an int.

FileOutputStream#write expects an int value. You could simply use a PrintWriter here instead which has an overloaded write method for writing String values :

PrintWriter writer = new PrintWriter(new FileOutputStream(file, false));
writer.write(...);

or to write each String on a new line use println

writer.println(...);

PLease try it.

     public static void main(String[] arg) throws IOException{
    File file=new File("C:\\file.txt");
    String text="myText";
    FileOutputStream fileOutputStream=new FileOutputStream(file);
    fileOutputStream.write(text.getBytes());
    fileOutputStream.close();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM