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());
}
Related
I am working on a text editor in Java as a fun side project. When I exported the project, I converted to executable JAR file to ".exe" so that I could set the text editor as the default program to open ".txt" files. I can run the ".exe" and write text and then save the file, and the file saves, but the contents of the file are not saved when I try to open the file with the text editor; however, I can open the same file with notepad, and the contents of the file show. The file saves fine in Eclipse. What do I need to fix so that the file contents are shown when I try to open them with my text editor?
Here is my code:
public class Open extends JFrame implements KeyListener {
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JMenuBar menuBar = new JMenuBar();
JMenu menu;
JMenuItem item;
Font systemFont;
public Open() {
systemFont = new Font("Times New Roman", Font.PLAIN, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(false);
textArea.setFont(systemFont);
panel.setLayout(new BorderLayout());
panel.add(scrollPane);
add(panel);
menu = new JMenu("File");
item = new JMenuItem("Save As");
item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
menu.add(item);
menuBar.add(menu);
menu = new JMenu("Edit");
item = new JMenuItem("Undo");
menu.add(item);
menu.add(item);
menuBar.add(menu);
add("North", menuBar);
setLookAndFeel();
frameDetails("Text Editor");
}
public void frameDetails(String title) {
setSize(700, 500);
setLocationRelativeTo(null);
setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setLookAndFeel() {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Open editor = new Open();
}
}
Here is the bit of code with the save button:
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
You are never reading the text file. In order to do that, Use something like this
public void loadFile(JTextArea area, String path, String file)
{
try
{
area.read(new FileReader(path + file), "Default");
}
catch(IOException e)
{
e.printStackTrace();
}
}
Note: You don't have to have this in a method. You could just use the try - catch code
To act as a default text editor, your program needs to accept a file name as the argument to main (String[] args). It should verify the file exists, then open it, read its contents, and close it.
Also, when you save a file you should rename the former version to "name.bak" or "name~" before overwriting it with the new version, in case something goes wrong during the save.
When I print a text that is in a JTextArea in a file it prints it in the same line . How can I add a new line in the file each time I have a new line in the JTextArea ?
This is my code .
print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null)== JFileChooser.APPROVE_OPTION){
File file = fileChooser.getSelectedFile();
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(valid.getText() );
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
Simply use this function from your BufferedWriter object:
bw.newLine();
This command isn't the same like: <br> or \n
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);
}
}
}
}
I need to have all the system.out.println statements to be displayed on the JTextArea when the copying is in progress. I tried giving ta.append instead of the println statements but it won't desplay. Please let me know how should I go about doing this.
public class copy {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Copy c = new Copy();
c.setTitle("Copy folders");
c.setVisible(true);
}
});
JPanel jp = new JPanel();
TextArea ta = new JTextArea(5, 50);
ta.setEditable(false);
DefaultCaret caret = (DefaultCaret) ta.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollPane = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(6, 625, 1035, 296);
jp.add(scrollPane); //Adding to JPanel
}
public Copy() {
build();
}
public void build() {
String source = "\\hostname\\d$\\somedirecotry";
String detination = "\\C:\\foldername";
File s = new File(source);
File s2 = new File(detination);
if (!s.exists()) {
System.out.println("Directory does not exist.");
} else if (!s2.exists()) {
System.out.println("Directory is not accessible or Server is down");
} else {
try {
copyFolder(s, s2);
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory copied from " + src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
//if file, then copy it
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
Swing is an event driven environment, this includes, but is not limited to, keyboard, mouse and paint events.
These events are delivered by the Event Dispatching Thread. Any operation (such as, but not limited to, loops, I/O or Thread#sleep) that blocks this thread will prevent (amongst other things) paint requests from begin processed. This will make your application stop responding to key and mouse events as well as make it look like its hung.
The easiest fix to your problem is to move the physical copy process to a separate thread. This is most easily accomplished by using a SwingWorker.
Take a look at Concurrency in Swing, in particular The Event Dispatch Thread and Worker Threads and SwingWorker
Examples can be found
JTextArea appending problems
SwingWorker with FileReader
JProgressBar won't update
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.