Java JTextPane RTF Save - java

i have the following code trying to save the contents of a JTextPane as RTF. although a file is created in the following code but it is empty!
any tips regarding what am i doing wrong? (as usual dont forget im a beginner!)
if (option == JFileChooser.APPROVE_OPTION) {
////////////////////////////////////////////////////////////////////////
//System.out.println(chooser.getSelectedFile().getName());
//System.out.println(chooser.getSelectedFile().getAbsoluteFile());
///////////////////////////////////////////////////////////////////////////
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
RTFEditorKit kit = new RTFEditorKit();
BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(chooser.getSelectedFile().getName()));
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
} catch (FileNotFoundException e) {
} catch (IOException e){
} catch (BadLocationException e){
}
}
EDIT: HTMLEditorKit if i use HTMLEditorKit it works and thats what i really wanted. SOLVED!

if (textPaneHistory.getText().length() > 0){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int option = chooser.showSaveDialog(ChatGUI.this);
if (option == JFileChooser.APPROVE_OPTION) {
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
HTMLEditorKit kit = new HTMLEditorKit();
BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(chooser.getSelectedFile().getAbsoluteFile()));
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
} catch (FileNotFoundException e) {
} catch (IOException e){
} catch (BadLocationException e){
}
}
}
here is the solution. it works if HTMLEditorKit is used.

Here is a solution for RTF and not HTML.
As RTF is not standardized, I needed some additional tags like \sb and \sa to force my Wordpad to display the file properly.
protected void exportToRtf() throws IOException, BadLocationException {
final StringWriter out = new StringWriter();
Document doc = textPane.getDocument();
RTFEditorKit kit = new RTFEditorKit();
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
out.close();
String rtfContent = out.toString();
{
// replace "Monospaced" by a well-known monospace font
rtfContent = rtfContent.replaceAll("Monospaced", "Courier New");
final StringBuffer rtfContentBuffer = new StringBuffer(rtfContent);
final int endProlog = rtfContentBuffer.indexOf("\n\n");
// set a good Line Space and no Space Before or Space After each paragraph
rtfContentBuffer.insert(endProlog, "\n\\sl240");
rtfContentBuffer.insert(endProlog, "\n\\sb0\\sa0");
rtfContent = rtfContentBuffer.toString();
}
final File file = new File("c:\\temp\\test.rtf");
final FileOutputStream fos = new FileOutputStream(file);
fos.write(rtfContent.toString().getBytes());
fos.close();
}

This is how I did when I faced the same problem.
public void actionPerformed(ActionEvent e) {
text = textPane.getText();
JFileChooser saveFile = new JFileChooser();
int option = saveFile.showSaveDialog(null);
saveFile.setDialogTitle("Save the file...");
if (option == JFileChooser.APPROVE_OPTION) {
File file = saveFile.getSelectedFile();
if (!file.exists()) {
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(file.getAbsolutePath() + ".rtf"));
writer.write(text);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null,
"Failed to save the file");
}
}
else if (file.exists()) {
int confirm = JOptionPane.showConfirmDialog(null,
"File exists do you want to save anyway?");
if (confirm == 0) {
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(file.getAbsolutePath()
+ ".rtf"));
writer.write(text);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null,
"Failed to save the file");
}
}
else if (confirm == 1) {
JOptionPane.showMessageDialog(null,
"The file was not saved.");
}
}
}
if (option == JFileChooser.CANCEL_OPTION) {
saveFile.setVisible(false);
}
}// End of method

The only problem I've seen in your code is that you're not closing the output stream (when content is actually written to disk).
Try out.close().
It should solve your problem.

Related

Opening a file without the extension - Java

Im doing a project for my college, my save/opening file are working all right, but I need them to save as my desired extension, and open like that as well.
For example: When I click on Save File, I write the name testFile as file name and hit save, now the my code must save as my desired extension. Same works for opening file, if I write testFile and hit open, it must locate the testFile.txt. Anyone can give me a hand how I should do this? follow my code below.
private class SalvaDesenho implements ActionListener {
private Component parent;
SalvaDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Arquivo de Texto (.txt)", "txt"));
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showSaveDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
return;
int op = 0;
if (fc.getSelectedFile().exists()) {
Object[] options = { "Sim", "Não" };
op = JOptionPane.showOptionDialog(null, "O arquivo já existe deseja substituilo?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
}
if (op != 0) return;
System.out.println("Salvando: " + fc.getSelectedFile().getPath());
FileOutputStream fout = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(figuras);
isSaved = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class AbreDesenho implements ActionListener {
private Component parent;
AbreDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter("Arquivo de texto (.txt)", "txt");
fc.setFileFilter(txtFilter);
int returnVal = fc.showOpenDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
System.out.println("File error!");
System.out.println("Abrindo: " + fc.getSelectedFile().getPath());
FileInputStream fin = new FileInputStream(fc.getSelectedFile());
ObjectInputStream ois = new ObjectInputStream(fin);
figuras = (Vector<Figura>) ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
pnlDesenho.getGraphics().clearRect(0 , 0, parent.getHeight(), parent.getWidth());
for (int i=0 ; i<figuras.size(); i++)
figuras.get(i).torneSeVisivel(pnlDesenho.getGraphics());
}
}
Thanks.
You have to do this manually:
Get the File object from the JFileChooser
Get its absolute path as a String, using getAbsolutePath().
Check whether it has an extension or not: Check file extension in Java
If not, add your extension to the path: path = path+".txt";
Create a new File object from the path: File file = new File(path)
Open/Save the file (your code)

How do I get a Text Area in Netbeans to display content that I already have saved in a Text File?

How do I get a Text Area in Netbeans to display content that I already have saved in a Text File? I want the text area txtAllOrders to display the content that I have in a text file Output.txt when I click on the button btnViewOrders.
I'm not a pro programmer in Java so pls correct me if I'm wrong, but I would try this:
FileInputStream fstream = new FileInputStream("YourFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String sw ="";
try
{
while(sw != null)
{
sw = br.readLine();
txtAllOrders.append(sw + "\n");
}
} catch (IOException ex) {
ex.printStackTrace();
}
Try to put the following code to the click event of your btnViewOrders
File file = new File("Output.txt");
FileInputStream fis = null;
String text = "";
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
text += (char) content;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
txtAllOrders.setText(text);

How to save desktop application state?

I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}

Append Images to RTF document

I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.

Data wrote using FileOutputStream disappear after restarting program

I'm learning java and I have made simple program that simply reads value from JTextField and saves it to file using FileOutputStream.
My question is: is it normal for data to be unreadable (using same program with FileInputStream) after restarting it? If i read it without terminating program it works fine.
How can I make data wrote to file permament?
Edit:
It seems the file is being cleaned when starting the program.
Here is the code:
public class Test extends JFrame
{
JTextField field;
JButton write;
JButton read;
File file;
FileOutputStream fOut;
FileInputStream fIn;
int x;
Test() throws IOException
{
setAlwaysOnTop(true);
setLayout(new BorderLayout());
field = new JTextField(4);
write = new JButton("Write");
read = new JButton("Read");
file = new File("save.txt");
if(!file.exists())
{
file.createNewFile();
}
fOut = new FileOutputStream(file);
fIn = new FileInputStream(file);
add(field);
add(write, BorderLayout.LINE_START);
add(read, BorderLayout.LINE_END);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(160,60);
write.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
x = Integer.parseInt(field.getText());
try
{
fOut.write(x);
System.out.println("Saving completed.");
fOut.flush();
}
catch(Exception exc)
{
System.out.println("Saving failed.");
}
}
});
read.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
x = fIn.read();
fIn.close();
}
catch(Exception exc)
{
System.out.println("Reading failed.");
}
}
});
}
public static void main(String[] args) throws IOException
{
new Test();
}
}
Make sure you flush() and close() the streams.
This fOut = new FileOutputStream(file); will overwrite the file, you need to use fOut = new FileOutputStream(file, true); to append to it.
here's some code to open a file for writing .. observe the "true" parameter which means we APPEND the text at the end instead of adding it to the start. The same goes for FileOutputStream .. if you don't specify the second argument (true) you will end up with an overwritten file.
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (IOException e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

Categories