I think you have a misconception about what a text file is. If you want to write a string of characters ( String
) - that is, plain text - to a file, the ideal is to have the format .txt
, so that it can be opened by a reader / editor of plain text , as is Notepad. However, a format file .pdf
is not designed to contain only plain text, but also formatted text, bitmaps and vector images.
If the file is in .pdf
format, it will be opened by a pdf reader, which will interpret its content as a specific pdf content, not plain text content. Therefore, if you create a .pdf
file in that way, with only plain text, the pdf reader will tell you that the file is damaged or that it could not read it.
In short, your method can only save files with plain text content. What you should do is put something like: "" C: \ Users \ pepitoperez \ Documents \ myText.txt "as file path, so that it is read by a plain text editor.
In this case, if you want to pass text to a file, you must convert the String
to a byte array ( byte[]
) and then to a file ( File
), so your method needs several adjustments.
- You do not have to write (write) byte byte.
FileOutputStream
already has a method to write an entire array of bytes: fos.write(arregloDeBytes)
.
- There is no need to throw the
FileNotFoundException, IOException
exceptions out of the method if you already handle them within it with the try-catch statement.
Convert bytes to a file
public static File convetirBytesAFile(String textoAGuardar, String rutaArchivo) {
bytes[] arregloDebytes = textoAGuardar.getBytes();
try (FileOutputStream fos = new FileOutputStream(rutaArchivo)) {
fos.write(arregloDeBytes);
} catch (FileNotFoundException nfe) {//manejo de la excepción archivo no encontrado
System.err.println("Archivo No encontrado.");
} catch (IOException oe) {//manejo de la excepción IO
System.err.println("Excepción de Escritura.");
}
return new File(rutaArchivo);
}
The code uses the try-with-resources statement, which automatically closes ( fos.close()
) the stream when the try-catch ends.
Now, if you want to save text in a PDF file you can use the Apache PDFBox library. It's easy to use:
public void textoAPDF(String texto) throws IOException{
PDDocument documentoPDF = new PDDocument();
PDPage pagina = new PDPage();
documentoPDF.addPage(pagina);
PDPageContentStream contentStream = new PDPageContentStream(documentoPDF, pagina);
contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.beginText();
contentStream.showText("Hola Mundo");
contentStream.endText();
contentStream.close();
documentoPDF.save("pdfBoxHolaMundo.pdf");
documentoPDF.close();
}