'Write a java program to read from a lengthy string (using streams) and write the output to a file?
How can I get a lengthy String as an input using streams and how to write the output to a file ?
Solution 1:[1]
/*
Here is another way you can perform the storage.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExample {
public static void main(String[] args) {
FileOutputStream fop = null;
File file;
String content = "This is the text content";//our you can take it
try {
file = new File("c:/newfile.txt");//File creation at C:/
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(fop!=null){
fop.flush();
fop.close();
}
}
Solution 2:[2]
Here is an example how you can read from a string and write it on output file and how you can read from a input file and write it on output file .
char stream to byte stream conversion and vice versa is also mentioned
package task;
import java.io.*;
//char -> byte (input - byte , output - char);
//byte -> char (input - char , output - byte);
// 1.You have to use OutputStreamWriter class for converting Character stream to Byte stream.
// 2.InputStreamReader class for converting Byte stream to Character stream,
// as these classes are used for stream conversions between two different streams.
public class Ques1{
public static void main(String args[]) throws IOException{
//byte stream
FileInputStream in = new FileInputStream("input.txt");
//FileOutputStream out = new FileOutputStream("output.txt");
//char stream
//FileReader in = new FileReader("input.txt");
FileWriter out = new FileWriter("output.txt");
try{
String s = "answet";
int i = 0;
while(i<s.length()){
out.write(s.charAt(i));
i++;
}
int t;
// while((t=(in.read()))!=-1){
// out.write(t);
// }
}
finally{
if(in!=null) in.close();
if(out!=null) out.close();
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sachin |
Solution 2 | Deepak Silver |