-
reading a file
What is the easies way to put the contents of a text file into a JTextArea? This is what I got so far.
try{
FileReader in = new FileReader(fileChooser.getSelectedFile());
int c;
textBox.setText("");
while ((c = in.read()) != -1) {
}
in.close();
}catch(java.io.IOException f){
-
:)
Code:
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class FileExample{
public static void main(String [] args){
JFrame jf = new JFrame("FileReader");
jf.addWindowListener(new WindowMonitor());
JTextArea jta = new JTextArea();
jta.setLineWrap(true);
jta.setWrapStyleWord(true);
Container c = jf.getContentPane();
c.add(jta);
jf.setSize(400,300);
jf.setVisible(true);
fill("C:\\Java\\Novice1.txt", jta);
}
public static void fill(String f, JTextArea jta){
try{
File file = new File(f);
BufferedReader buff = new BufferedReader(new FileReader(file));
char[] c = new char[getFileCharCount(f)];
Character[] C = new Character[c.length];
int charsread;
while(true){
charsread = buff.read(c);
if(charsread == -1) break;
}
for(int i = 0; i < c.length; ++i){
C[i] = new Character(c[i]);
jta.append(C[i].toString());
}
}catch(IOException e){System.err.println(e);}
}
public static int getFileCharCount(String file) {
String lineOnebyOne = null;
String finalText = null;
int numberOfChar = 0;
try{
BufferedReader br = new BufferedReader(new FileReader(file));
while ((lineOnebyOne = br.readLine ())!= null){
finalText += lineOnebyOne;
numberOfChar = finalText.length();
}
br.close();
}catch(IOException e){System.err.println(e + "getFileCharCount");}
return numberOfChar;
}
}
class WindowMonitor extends WindowAdapter {
public void windowClosing(WindowEvent e){
System.exit(0);
}
}