import java.io.FileOutputStream;
import java.io.File;
public class AppendBinaryFile
{
public static void main (String[] args)
{
FileOutputStream toFile = null;
try
{
toFile = new FileOutputStream(new File("numbers.dat"), true);
toFile.write(15);
toFile.write(30);
toFile.close();
}
catch (Exception e)
{
}
}
}
I run another program to get the data from a binary file after running the program but data in the binary file does not change. What is wrong with the code?
You need to close your file output stream I believe.
Related
I am trying to convert docx to pdf using docx4j 3.7.7.The issue is pdf is getting generated properly but the docpropery having cyrillic text is not coming up. It coming as #####. Normal paragraph with cyrillic text is getting generated properly. The issue is reproducible only in linux. In windows, docProperty is getting converted properly.
The file for testing can be found here
file
Below is the code :
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.docx4j.Docx4J;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class TestRussian {
public static void main(String[] args) {
new TestRussian().convertWordToPdf();
}
public void convertWordToPdf() {
FileOutputStream fileOutputStream =null;
try {
File file = new File("Test1.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
boolean checkViaFo = Docx4J.pdfViaFO();
FOSettings foSettings = Docx4J.createFOSettings();
fileOutputStream= new FileOutputStream("PDFRussian1.pdf");
foSettings.setWmlPackage(wordMLPackage);
//Getting error in update() during complex field update
//FieldUpdater updater = new FieldUpdater(wordMLPackage);
//updater.update(true);
Docx4J.toPDF(wordMLPackage,fileOutputStream);
System.out.println("Done");
} catch (Exception ex) {
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
}
}
}
}
I have read something about MERGEGORMAT & CHARFORMAT but didnt have much idea on that
I am a beginner in Java and trying to learn the basics of FileInputStream and FileOutputStream. I was able to successfully write the data to the file but unable to read it. Here is my code. Could you please let me know, if I am missing something to read the data.
Application.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Application {
public static void main(String[] args) throws FileNotFoundException {
try(FileOutputStream fs = new FileOutputStream("testdata.txt")){
ObjectOutputStream os = new ObjectOutputStream(fs);
MathematicalOperation mo = new MathematicalOperation();
os.writeObject(mo);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ReadingFile.Java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ReadDataFromFile {
public static void main(String[] args) throws FileNotFoundException{
try(FileInputStream fi = new FileInputStream("testdata.txt")){
ObjectInputStream oi = new ObjectInputStream(fi);
MathematicalOperation mo= (MathematicalOperation) oi.readObject();
System.out.println(mo);
oi.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
If you're trying to read the content of the .txt file, just use FileInputStream class.
Also, it would be of great help if you coul
While writing to the file "testdata.txt" you are passing object of MathematicalOperation class, you can set values of the class members before writing file (e.g. mo.setXXX()) and when you are reading that object from text file you can get those values using the return object of MathematicalOperation (e.g. mo.getXXX()) and before printing the object please override toString() method in your MathematicalOperation class to display the correct values of all fields of the class.
public class Fileverifynanoha
{
private File fileext;
private Path filepath;
public Fileverifynanoha()//this class wants to create a file, write something, and close it.
{
filepath = Paths.get("./txttest.txt");
Charset charset = Charset.forName("US-ASCII");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
try (BufferedWriter filewriter = Files.newBufferedWriter(filepath,charset))
{
filewriter.write(s,0,s.length()-1);
}
catch(IOException e)
{
System.err.println(e);
}
}//end of this class
/**
* #param args the command line arguments
*/
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
if (filetxt.exists()&&!filetxt.isDirectory())//object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Here is the code. I want to use the class I create to create a file, write something. Then, I use main class to check if that file exist.
However, I don't know why, but the main class does not recognise my (maybe) created file. Could anyone tell me how to link them together?
I know there may be some minor bugs in this program. I will fix that later.
Thanks.
You never called your constructor.
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha fvn = new Fileverifynanoha();
if (fvn.filetxt.exists()&&!fvn.filetxt.isDirectory())
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Your issues:
Didn't create instance of class.
Didn't init File file, so it would be null always.
Better use utf-8 for plain text file.
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Fileverifynanoha {
private File file;
private Path path;
public Fileverifynanoha(String fp) {
this.path = Paths.get(fp);
this.file = path.toFile();
}
public void createFile()// this class wants to create a file, write something, and close it.
{
Charset charset = Charset.forName("UTF-8");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
BufferedWriter filewriter = null;
try {
filewriter = Files.newBufferedWriter(path, charset);
filewriter.write(s, 0, s.length() - 1);
filewriter.close();
} catch (IOException e) {
System.err.println(e);
}
}// end of this class
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)// the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha f = new Fileverifynanoha("./txttest.txt");
f.createFile();
if (f.file.exists() && !f.file.isDirectory())// object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
} else {
System.out.println("File does not exist.");
}
}
}
I have gone through all the related posts in this forum and also googled but not found the exact answer.
When running the below code, I get following error:
The constructor BufferedWriter(FileWriter) is undefined
The constructor FileWriter(String) is undefined
public class FileWriter {
public static void main(String[] args) {
BufferedWriter f = null;
try
{
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
f.close();
}
}
}
I guess you want to use java.io.FileWriter class of java but you redefine it. You can rename your class to something else more meaningful.
You have to import your used classes like BufferedWriter. That's why you get your undefined errors.
Also it is a good practice to check if the writer f is null before closing:
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
BufferedWriter f = null;
try {
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e) {
System.out.println(e);
}
finally {
if (f != null)
f.close();
}
}
}
Your class is called FileWriter which conflicts with the name of the java.io.FileWriter. Rename your class something else and then explicitly import the java.io.FileWriter and java.io.BufferedWriter classes.
import java.io.FileWriter;
import java.io.BufferedWriter;
I would also suggest using a more modern idiom: try-with-resources, which automatically closes the writer for you. It's terser and cleaner.
public class Example {
public static void main(String... args) throws Exception {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\A.txt")) {
writer.write("Hello World");
}
}
}
use these steps. This is the correct and easy way to use buffered writer.
1.create File object.
File f = new File(C://A.txt);
create file writer object.
FileWriter fr = new FileWriter(f);
create Buffered writer .
BufferedWriter bw = new BufferedWriter(fr);
4.then you can easily write to the file like below.
bw.write("Hello World");
hope this will be help to you
remember to import
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;
those packages will be automatically suggest if you are using ide like netbeans.
I've read the documentation and the examples but I'm having a hard time putting it all together. I'm just trying to take a test pdf file and then convert it to a byte array then take the byte array and convert it back into a pdf file then create the pdf file onto disk.
It probably doesn't help much, but this is what I've got so far:
package javaapplication1;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
public class JavaApplication1 {
private COSStream stream;
public static void main(String[] args) {
try {
PDDocument in = PDDocument.load("C:\\Users\\Me\\Desktop\\JavaApplication1\\in\\Test.pdf");
byte[] pdfbytes = toByteArray(in);
PDDocument out;
} catch (Exception e) {
System.out.println(e);
}
}
private static byte[] toByteArray(PDDocument pdDoc) throws IOException, COSVisitorException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
pdDoc.save(out);
pdDoc.close();
} catch (Exception ex) {
System.out.println(ex);
}
return out.toByteArray();
}
public void PDStream(PDDocument document) {
stream = new COSStream(document.getDocument().getScratchFile());
}
}
You can use Apache commons, which is essential in any java project IMO.
Then you can use FileUtils's readFileToByteArray(File file) and writeByteArrayToFile(File file, byte[] data).
(here is commons-io, which is where FileUtils is: http://commons.apache.org/proper/commons-io/download_io.cgi )
For example, I just tried this here and it worked beautifully.
try {
File file = new File("/example/path/contract.pdf");
byte[] array = FileUtils.readFileToByteArray(file);
FileUtils.writeByteArrayToFile(new File("/example/path/contract2.pdf"), array);
} catch (IOException e) {
e.printStackTrace();
}