How to open a file in a JTextArea

hi..
m having difficulty in opening a file in a textarea..if anyone could help me out..
Parul

I hope the code below will solve ur problem,Parul --------
This program lets the user edit short text files in a window. A "File"
menu provides the following commands:
New -- Clears all text from the window.
Open -- Let's the user select a file and loads up to 100
lines of text form that file into the window. The
previous contents of the window are lost.
Save -- Let's the user specify an ouput file and saves
the contents of the window in that file.
Quit -- Closes the window and ends the program.
This class uses the non-standard class TextReader.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrivialEdit extends JFrame {
public static void main(String[] args) {
// The main program just opens a window belonging to this
// TrivialEdit class. Then the window takes care of itself
// until the program is ended with the Quit command or
// when the user closes the window.
new TrivialEdit();
private JTextArea text; // Holds the text that is displayed in the window.
public TrivialEdit() {
// Add a menu bar and a JTextArea to the window, and show it
// on the screen. The first line of this routine calls the
// constructor from the superclass to specify a title for the
// window. The pack() command sets the size of the window to
// be just large enough to hold its contents.
super("A Trivial Editor");
setJMenuBar(makeMenus());
text = new JTextArea(25,50);
text.setBackground(Color.white);
text.setMargin( new Insets(3,5,0,0) );
JScrollPane scroller = new JScrollPane(text);
setContentPane(scroller);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocation(50,50);
show();
private JMenuBar makeMenus() {
// Create and return a menu bar containing a single menu, the
// File menu. This menu contains four commands, and each
// command has a keyboard equivalent.
ActionListener listener = new ActionListener() {
// An object that will serve as listener for menu items.
public void actionPerformed(ActionEvent evt) {
// This will be called when the user makes a selection
// from the File menu. This routine just checks
// which command was selected and calls another
// routine to carry out the command.
String cmd = evt.getActionCommand();
if (cmd.equals("New"))
doNew();
else if (cmd.equals("Open..."))
doOpen();
else if (cmd.equals("Save..."))
doSave();
else if (cmd.equals("Quit"))
doQuit();
JMenu fileMenu = new JMenu("File");
JMenuItem newCmd = new JMenuItem("New");
newCmd.setAccelerator( KeyStroke.getKeyStroke("ctrl N") );
newCmd.addActionListener(listener);
fileMenu.add(newCmd);
JMenuItem openCmd = new JMenuItem("Open...");
openCmd.setAccelerator( KeyStroke.getKeyStroke("ctrl O") );
openCmd.addActionListener(listener);
fileMenu.add(openCmd);
JMenuItem saveCmd = new JMenuItem("Save...");
saveCmd.setAccelerator( KeyStroke.getKeyStroke("ctrl S") );
saveCmd.addActionListener(listener);
fileMenu.add(saveCmd);
JMenuItem quitCmd = new JMenuItem("Quit");
quitCmd.setAccelerator( KeyStroke.getKeyStroke("ctrl Q") );
quitCmd.addActionListener(listener);
fileMenu.add(quitCmd);
JMenuBar bar = new JMenuBar();
bar.add(fileMenu);
return bar;
} // end makeMenus()
private void doNew() {
// Carry out the "New" command from the File menu by
// by clearing all the text from the JTextArea.
text.setText("");
private void doSave() {
// Carry out the Save command by letting the user specify
// an output file and writing the text from the JTextArea
// to that file.
File file; // The file that the user wants to save.
JFileChooser fd; // File dialog that lets the user specify the file.
fd = new JFileChooser(new File("."));
fd.setDialogTitle("Save Text As...");
int action = fd.showSaveDialog(this);
if (action != JFileChooser.APPROVE_OPTION) {
// User has canceled, or an error occurred.
return;
file = fd.getSelectedFile();
if (file.exists()) {
// If file already exists, ask before replacing it.
action = JOptionPane.showConfirmDialog(this,
"Replace existing file?");
if (action != JOptionPane.YES_OPTION)
return;
try {
// Create a PrintWriter for writing to the specified
// file and write the text from the window to that stream.
PrintWriter out = new PrintWriter(new FileWriter(file));
String contents = text.getText();
out.print(contents);
if (out.checkError())
throw new IOException("Error while writing to file.");
out.close();
catch (IOException e) {
// Some error has occured while trying to write.
// Show an error message.
JOptionPane.showMessageDialog(this,
"Sorry, an error has occurred:\n" + e.getMessage());
private void doOpen() {
// Carry out the Open command by letting the user specify
// the file to be opened and reading up to 100 lines from
// that file. The text from the file replaces the text
// in the JTextArea.
File file; // The file that the user wants to open.
JFileChooser fd; // File dialog that lets the user specify the file.
fd = new JFileChooser(new File("."));
fd.setDialogTitle("Open File...");
int action = fd.showOpenDialog(this);
if (action != JFileChooser.APPROVE_OPTION) {
// User canceled the dialog, or an error occurred.
return;
file = fd.getSelectedFile();
try {
// Read lines from the file until end-of-file is detected,
// or until 100 lines have been read. The lines are added
// to the JTextArea, with a line feed after each line.
TextReader in = new TextReader(new FileReader(file));
String line;
text.setText("");
int lineCt = 0;
while (lineCt < 100 && in.peek() != '\0') {
line = in.getln();
text.append(line + '\n');
lineCt++;
if (in.eof() == false)
text.append("\n\n******* Text truncated to 100 lines! *******\n");
in.close();
catch (Exception e) {
// Some error has occured while trying to read the file.
// Show an error message.
JOptionPane.showMessageDialog(this,
"Sorry, some error occurred:\n" + e.getMessage());
private void doQuit() {
// Carry out the Quit command by exiting the program.
System.exit(0);
} // end class TrivialEdit
Amit Gupta

Similar Messages

  • How to open a file created at the server through form/report at client end

    How to open a file created at the server through form/report at client end
    Dear Sir/Madame,
    I am creating a exception report at the server-end using utl file utility. I want to display this report at the client end. A user doesn't have any access to server. Will u please write me the solution and oblige me.
    Thanks
    Rajesh Jain

    One way of doing this is to write a PL/SQL procedure that uses UTL_FILE to read the file and DBMS_OUTPUT to display the contents to the users.
    Cheers, APC

  • HT4796 I have made a file using the Pages app.I mailed it to a friend.When she tried opening the same file on her pc at home , It did not open.Please help me as to how to open the file in the Microsoft word format on her pc.

    I have made a file using the Pages app.I mailed it to a friend.When she tried opening the same file on her pc at home , It did not open.Please help me as to how to open the file in the Microsoft word format on her pc.

    Send it as a PDF.

  • How to open CR2 files in photoshop elements 10

    Who knows how to open CR2-files from a Canon Powershot S100 in Photoshop Elements 10?

    Hi,
    The version of Camera Raw that you reported should support the S100 CR2 images.
    If you load the editor, go to the File menu and select Open, then point to the file, are you saying that it displays the error message?
    Have you tried opening the file with Canon's Zoombrowser?
    Which operating system are you running on?
    Brian

  • How to open *.pdf files in BOXI r2 inbox

    I am scheduling as  *.pdf file for deski report.After scheduling i am getting *.pdf in my inbox.if the report is deski or webi we can use FC_REPORT_ENGINE or WI_REPORT_ENGINE to open the report's using java code.In same way how to open *.PDF file in Inbox?
    Edited by: ramkishore kishore on Nov 7, 2008 8:31 AM
    Edited by: ramkishore kishore on Nov 7, 2008 8:31 AM

    Hi Ram,
    Following information might help you to resolve the issue.
    After logging into Desktop Intelligence, you may be presented with a message stating:
    u201CYou have received 1 document from users"
    Examining the Inbox from within the Desktop Intelligence client shows no objects visible in your Inbox.
    The object in your Inbox is in a format other than Desktop Intelligence format such as, PDF, XLS or other format. Therefore the object is not recognized by the Desktop Intelligence client inbox browser.
    Log in to Info View or the Central Management Console, browse to your Inbox and verify the file name and format that has been sent to your Inbox. The object may be saved, copied, moved or deleted as necessary.
    Regards,
    Sarbhjeet Kaur

  • How to open NRW-files in Lightroom 4?I

    just bought Nikon's Coolpix P7800. It says you can shoot in Raw. Now I want to open these files in LR, just like I'm used to with my SLR's. But Nikon uses the NRW-format for Raw and LR says it doesn't recognise the files. Does someone know if there's a way to convert and work with these files in LR 4?

    Thanks Jim for your response,
    I will upgrade to 5.3
    Kind regardsEut van Berkum
         Op woensdag 28 januari 17:04 2015 schreef JimHess <[email protected]> het volgende:
    how to open NRW-files in Lightroom 4?I
    created by JimHess in Photoshop Lightroom - View the full discussionThe only way to use those files with Lightroom 4 is to convert them to DNG using DNG converter 8.3 or higher. The camera wasn't supported in Lightroom until version 5.3. If the reply above answers your question, please take a moment to mark this answer as correct by visiting: https://forums.adobe.com/message/7140310#7140310 and clicking ‘Correct’ below the answer Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: Please note that the Adobe Forums do not accept email attachments. If you want to embed an image in your message please visit the thread in the forum and click the camera icon: https://forums.adobe.com/message/7140310#7140310 To unsubscribe from this thread, please visit the message page at , click "Following" at the top right, & "Stop Following"  Start a new discussion in Photoshop Lightroom by email or at Adobe Community For more information about maintaining your forum email notifications please go to https://forums.adobe.com/thread/1516624.

  • How to open aspx. files in OS 10.8?

    is this the right place to ask how to open aspx. files in OS 10.8.2?

    Unfortunately aspx is a generic extender - it is a report generated by a server running Windows .net - it isn't an extender that actually tells what kind of file it is or what kind of data it holds. That's something you either have to know before hand so you can force the proper program to open it (or change the aspx extender to its real extender) or you have to find out what the file is.
    At work our system's report generator gives everything an aspx extender. When I generate a report I decide whether it should be a PDF, Excel file, etc. After downloading the file I change its extender appropriately.

  • How to open Zip Files in N900 ?

    Hi Guys,
    I wanted to know how to open Zip files in N900 ? is there a App available for it or what ?
    Thanks

    if you have rootsh installed, open up xterm and run these commands
    root
    apt-get install unzip-fm
    apt-get install unrar-fm
    as in the link from aspergerguy, you need the extra catalogs installed.
    once you have them installed you just need to click on the zipped file then it will unzip it to a folder of the same name

  • How to open raw files in elements 11

    how to open raw files in elements 11

    Hi Have tried to do that but get a box with message along top "The file aready exists in the catalog"  it is also showing the incorrect file path and saying not connected to the path I have found the photo in.  The only differenct is that elements it saying it is in E drive and I have it in C drive the rest of the path is the same.
    The photos have imported into the my folders but I can't open any, every one i've tried to open brings up the box "searching for missing file" There are no photos in E drive the path it is saying doesn't exist all photos are in c drive, very very frustrating

  • How to open .vnt files in iphone

    how to open .vnt files in iphone

    virtualscott wrote:
    I was revisiting the WWDC from June and Jobs mentioned the ability view
    iWork files on the iPhone. I have done a lot of searching and have not
    found any answers. Can someone help, please?
    You can view them as email attachments.

  • How to open TIF files in iPad

    How to open TIF files in iPad

    The Mail ap can handle TIFF files for viewing purposes. They can be saved to the Photos app (from Mail, or other apps such as DropBox), but I beleive they get converted to JPG in the process. There are also a number of third party apps that can at least view TIFF files.
    If you could describe exactly what it is you are trying to accomplish, someone may be able to provide more detailed assistancce.

  • How to open psb files in mac

    how to open psb files in mac

    No it isn't free but you can download a free trial version.
    http://www.adobe.com
    Afterward you can download GIMP it is free and will also change your PSB files.
    http://www.gimp.org

  • How to open sdf files in SQL server 2012?

    How to open sdf files in SQL server 2012?
     I couldn’t figure out how to open the sdf files in SQL server 2012
     Thank you
     Best
     Jamal

    I don't think it's hard if understood the question properly you can try this I do it most of the time and this might be the solution for you, sometimes minor simple click is a life saver:)
    1. 
    Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer... and click the
    connect drop down arrow
    2. 
    In the Connect to Server dialog you will see Database Enghine, Analaysis Servie on so on and you go head change Server type to
    SQL Server Compact Edition
    3. 
    From the Database file drop-down as shown below click the drop down arrow and select <
    Browse for more...>
    4. 
    And you will see C:\, D:\, G:\
    drive and so on and open, your SDF file where it is located
    I hope this has been informative for you and good luck
    Please remember to click “Mark as Answer” on the post that has answered your question as it is very relevant to other community members dealing with same problem in seeking the right answer

  • How to open the file types of iOSApp(ipa),EPUBFile(.epub) in windows 7(32 bit)

    How to open the file types of iOSAPP(ipa),EPUBfile(.epub) in windows 7(32 bit)

    iOS apps can be added to an iTunes library and thereafter transferred to an iOS device. They cannot be opened directly on a PC.
    epub files can be added to an iTunes library, and thereafter transferred to an iOS device where they can be read with the iBooks application. Files protected with Apple's DRM cannot be opened directly on a PC, though there are programs such as Kindle and Calibre that will open non-protected epub files.
    tt2

  • HOW TO OPEN WINDAT FILES

    How to open windat files which come along with E mails from microsoft users ?

    That is priceless, "you can ignore winmail.dat...."  No I can't. They are often a drawing or purchase order I require for a job.
    I am running outlook on my mac and I still can't open them. All my other devices open these attachments no problem (none of them are apple). The people sending me these attachments are using macs. The only thing that has changed since I started encountering this problem is my hardware. I still use outlook, I have the same email address. The PDF attachments are being sent by the same people in the same way. When I had an iphone they opened on there too. Why do all the people on this forum keep blaming microsoft. Why can't macs read microsoft RTF, much like gmail or yahoo manage to do.
    I cannot go asking busy project managers to send me attachments in a different format simply because I bought what I thought to be a decent computer.

Maybe you are looking for

  • Premiere Elements 11 - No Burners Detected

    Hi All, When I try and burn a project to DVD I get the error showing on screen 'No Burners detected' - if i choose AVCHD the burner shows up. I am running windows 7 64bit. Any ideas how to fix this issue. Sean

  • Adding Classes to the JAR File's Classpath

    Ques 1- Can I use the wildcard * symbol in Manifest file to add classes/othes jar files to the JAR File's Classpath.I have folder named - Lib . where there are many jar files.Now,do I have to add each jar file by- Class-Path: Lib/jar1-name Lib/jar2-n

  • Download the entire component in web ui

    how can we download the entire component in web ui?

  • AppsLocalLogin.jsp

    How do I add a mailto link to the AppsLocalLogin.jsp page Thank you in advance!!

  • Sincronización de contactos con iCloud

    hola, los contactos creados en mi mac si se actualizan en mi iphone, pero contactos creados en mi Iphone no se actualizan en mi mac, que hago para que todo se sincronice? hay un número finito de contactos que pueda actualizar icloud? que pasa si teng