Code To Write A String Into A File
Code To Write A String Into A File
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
String phrase = new String("my name is mohit ");
File aFile = new File("test.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File stream created successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("New buffer: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
// Load the data into the buffer
for (char ch : phrase.toCharArray()) {
buf.putChar(ch);
}
System.out.println("Buffer after loading: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
buf.flip();
System.out.println("Buffer after flip: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
try {
outChannel.write(buf);
outputFile.close();
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hiii");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
When it comes to reading Microsoft Office Word document Java does not have any in
build classes to handle this but Apache POI Package developed by Apache Foundation
gives you the power of reading Microsoft Word document in Java. More information on
the Apache POI package can be found at Apache POI
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.extractor.*;
import java.io.*;
POIFSFileSystem fs = null;
try
paragraphs[i] =
paragraphs[i].replaceAll("\\cM?\r?\n","");
System.out.println( "Length:"+paragraphs[ i
].length());
catch(Exception e) {
e.printStackTrace();
POI libraries