2

I've seen a lot of websites that describe how to append text into a textarea, but is there a way to grab data from a whole .txt file and display it in the textarea?

I've been playing around with various things to put into a line like this:

outputTextArea.append(????);

But no luck yet.

Super new to java and not so good with the terminology but I hope I explained my question well.


EDIT: It won't let me respond to my own question, so I'm just going to put it up here.

I am using JTextArea, but I guess I'm a little overwhelmed. I'm not entirely sure what I'm seeing, but is this what you were talking about?

public FileReader(String fileName);

I've got this so far.

FileWriter fwriter = new FileWriter("BigMoneys.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);

for (int year = 1; year<= 10; year++)
{
    amount = principal * Math.pow(1.0 + rate, year);
    outputFile.append( year + "\t" + moneyFormat.format(amount) + "\n");

}

outputFile.close();

JOptionPane.showMessageDialog(null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE);

System.exit(0);

The rest of this was covered in my textbook fairly well, and all makes decent sense, but I just checked and the book has nothing about FileReader.

All I know is I'm supposed to use what's in outputFile and append it to outputTextArea. I'm honestly not trying to get you to do my homework for me, I'm just really really lost.

So if I am supposed to use that line above, could I do this?

FileReader(String fwriter)


EDIT2: This is what I've got so far. Please tell me if I'm on the right track.

import java.util.Scanner;
import java.io.*;
import java.text.NumberFormat;  //class for numeric formatting
import java.util.Locale;        //class for country-specific information
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class Interest3
{
    public static void main(String[] args) throws IOException
    {
        double amount,  //amount of deposit at end of each year
            principal,  //initial amount before interest
            rate;       //rate of interest
        String input;
        String filename;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter the filename: ");
        filename = keyboard.nextLine();

        //create NumberFormat for currency in US dollar format
        NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );

        //create JTextArea to display output
        JTextArea outputTextArea = new JTextArea();

        input = JOptionPane.showInputDialog("Please enter Principal: ");
        principal = Double.parseDouble(input);

        input = JOptionPane.showInputDialog("Please enter Interest Rate (Format: 0.00) ");
        rate = Double.parseDouble(input);

        outputTextArea.setText("Year\tAmount on deposit\n");

        //open new file for writing
        PrintWriter outputFile = new PrintWriter(filename);

        //calculate amount on deposit for each of ten years
        for (int year = 1; year<= 10; year++)
        {
            amount = principal * Math.pow(1.0 + rate, year);

            // append one line of text to outputTextArea
            outputFile.append( year + "\t" + moneyFormat.format(amount) + "\n");

        }

        outputFile.close();

        //open file for reading
        File file = new File(filename);
        FileReader rd = new FileReader(file);

        outputTextArea.append(rd);

        //display results
        JOptionPane.showMessageDialog(null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE);

        System.exit(0);
    }

}

I've got an error on the line with outputTextArea.append(rd); that says "append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.io.FileReader)", so I'm obviously missing something down there.


EDIT3: Aaaand I think I've got it! Thanks for everyone's help. Case closed, goodnight :)

DianaMelee
  • 21
  • 1
  • 5
  • If you are prepared to use a `JEditorPane`, see [this short example](http://stackoverflow.com/questions/7411543/accessing-file-from-package/7411958#7411958). – Andrew Thompson Sep 14 '11 at 09:46
  • I've only been learning java for 5 weeks, so no, I don't think I'm prepared for that, but I will definitely bookmark it. It'll probably come in handy somewhere down the line. Thanks. – DianaMelee Sep 14 '11 at 10:35

6 Answers6

3

As this is not a "plz can I haz de codez" site I am not going to give code for doing that. Instead, here's a couple of pointers:

  1. Use FileReader or something similar to read the file, and put the contents into a string.
  2. You can then append it to the end of your JTextArea as suggested.

PS you may want to consider JTextArea and Swing instead of plain AWT.

Also see:

How to Use Text Areas

Character Streams

Ashkan Aryan
  • 3,504
  • 4
  • 30
  • 44
  • Had to edit my original post in order to respond. Trying to not sound like an idiot, I swear. – DianaMelee Sep 14 '11 at 10:28
  • You don't need to use filewriter. You need to READ your file using your file reader, stick into a string, and append it to your JTextArea – Ashkan Aryan Sep 14 '11 at 10:35
  • see http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file or this http://snippets.dzone.com/posts/show/3526 – Ashkan Aryan Sep 14 '11 at 10:38
  • I understand what you were trying to tell me, I just don't know how to go about it. Don't I have to use FileWriter to get the loop data into a txt file before I can use FileReader to put it in a string? – DianaMelee Sep 14 '11 at 10:57
  • So... `FileReader read = new FileReader("BigMoneys.txt");`? Could I put that underneath my PrintWriter? – DianaMelee Sep 14 '11 at 11:13
  • You don't need a printwriter, you are not writing to a file. – Ashkan Aryan Sep 14 '11 at 11:15
  • I don't? I thought I had to start with the user inputting their starting balance and interest rate, go through the loop to calculate how much money they'll have after 10 years, write that data into a txt file, (missing step), append it to the outputTextArea variable , and then have it pop up in a JOptionPane message dialog. – DianaMelee Sep 14 '11 at 11:21
  • Alright. I'm obviously not getting it. I've been trying to use the two examples from above to make mine work, but I'm getting nowhere. Can you please be a little more specific? – DianaMelee Sep 14 '11 at 12:04
  • Well I don't know what exactly you are trying to do or what your question/homework is! The advice I gave was on how to read from a file and append to a JTextArea, don't know what else you need to do! – Ashkan Aryan Sep 14 '11 at 12:17
  • I'm sorry this is so frustrating. I need to read from a file that I created earlier in the code. So I need both a FileWriter and a FileReader, yes? These were the specific instructions: 1) Ask the user for initial principal amount and annual percentage rate. 2) Program will go through the for-loop but instead of displaying in the screen, write to a text file. 3) Program will then open the same text file, read the data and append to the outputTextArea variable and then JOption display on the screen inside a JOptionPane message dialog. – DianaMelee Sep 14 '11 at 12:29
2

Why don't you write the text to your JTextArea at the same time you write it to a File:

FileWriter fwriter = new FileWriter("BigMoneys.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);
for (int year = 1; year<= 10; year++) {
    amount = principal * Math.pow(1.0 + rate, year);
    String line = year + "\t" + moneyFormat.format(amount) + "\n";
    outputTextArea.append(line);
    outputFile.append(line);
}
outputFile.close();
JOptionPane.showMessageDialog(null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE);
System.exit(0); 

That shall work.

Please note, however, that this would not be the best way to design an application, which would require to split your applications in layers, but I don't want to enter into this, because you obviously don't know enough about Java to go further in that direction.

jfpoilpret
  • 10,449
  • 2
  • 28
  • 32
  • Woah. That's awesome! That's exactly what Ashkan was saying this whole time but I just had no idea how or where to write it. You're a life saver. – DianaMelee Sep 14 '11 at 12:45
  • This is not entirely correct as your original instruction stipulates that you first write to the file and then read back to it (see step 2 and 3 in your comments to my answer) but this answer does NOT read back from the file. – Ashkan Aryan Sep 14 '11 at 12:53
  • Oh.. yeah. I guess not. Guess I'm not sleeping tonight. – DianaMelee Sep 14 '11 at 12:59
1

Read the file and store its content into a String, and then append the String to the text area.

You won't find any shortcut method in (J)TextArea to read the file for you, because that's not his business. The text could come from a file, a database, a socket connection or anywhere else. That's not the responsibility of the text area to read the text from all these potential locations. Its responsibility is to display the text you give it.

So read the text file yourself. See the Java tutorial about character streams.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • -1 All text components support a read(...) method. A write() method is also supported. These two methods work together to make sure the proper line return string is used in the file. However, the read() will create a new Document so it can't be used for an append(). To do an append you can use the EditorKit (see my answer below). – camickr Sep 14 '11 at 15:37
1

Focusing only on the problem "reading content from a file and put it into a JTextArea", here is what you need:

//open file for reading
File file = new File(filename);
BufferedReader rd = new BufferedReader(new FileReader(file));
String line;
while ((line = rd.readLine()) != null)
    outputTextArea.append(line + "\n");
rd.close();
//display results
JOptionPane.showMessageDialog(null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE);

Note that I sue a BufferedReader so that the file can be read line per line, rather than reading it completely in one time, which in fact would lead to more complicated code.

jfpoilpret
  • 10,449
  • 2
  • 28
  • 32
  • Program just stops after it asks for the filename. Doesn't say it's completed, just blinks. – DianaMelee Sep 14 '11 at 13:55
  • Alright, well I got it running at least, but it's giving me this message: `Enter the filename: asdf Exception in thread "main" java.io.FileNotFoundException: asdf (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:120) at java.io.FileReader.(FileReader.java:55) at Interest3.main(Interest3.java:53) Process completed.` – DianaMelee Sep 14 '11 at 14:27
1

You can use the EditorKit to do this for you:

JTextArea edit = new JTextArea(...);
...
try
{
    FileReader reader = new FileReader( "TextAreaLoad.txt" );
    BufferedReader br = new BufferedReader(reader);
    EditorKit kit = edit.getUI().getEditorKit(edit);
    Document doc = edit.getDocument();
    kit.read(br, doc, doc.getLength());
    br.close();
}
catch(Exception e2) { System.out.println(e2); }
camickr
  • 321,443
  • 19
  • 166
  • 288
-1

There is a JProgressBar demo included in the JDK (folder demo/jfc/SwingSet2) which seems correspond to what you want. Source code is provided also.

Laurent Legrand
  • 1,104
  • 6
  • 6