Reading a text File into a JTextArea

I know this is really basic question, but what is the best and/or simplest way to read text from a .txt file into a JTextArea? I'm new to Java and any help anyone can provide would be greatly appreciated.

it should be in quotes only if it is a string repersentation of a String class.
FileReader reader = new FileReader("readme.txt");
quotes are not needed if you write it this way
String filename = "readme.txt";
FileReader reader = new FileReader(filename);
...remember that String is a class and not a data type, it is also a special case in java where the class can act like a datatype in declarations.
I don't think anything else can behave like this in java
String text = "sometext";
"sometext".equals(text);
this returns true.

Similar Messages

  • Open and read from text file into a text box for Windows Store

    I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
    Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
    Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
    Thanks
    Wendel

    This is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using System.IO;
    namespace TextFileDemo
    public class TextFileHelper
    async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
    StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    show how to use it as below
    async private void Button_Click(object sender, RoutedEventArgs e)
    string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
    Debug.WriteLine(txt);
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • Convert a line read from text file into string

    how to convert a line from text file into string?
    i know how to convert to numbers,
    private int  parseLine1(String line) {
              StringTokenizer tokenizer = new StringTokenizer(line);
                  value1 = Integer.valueOf(tokenizer.nextToken()).intValue();
                  value2 = Integer.valueOf(tokenizer.nextToken()).intValue();
                 return value1;
                     }but what about charactrs?

    ok, here is my problem, i have a file with a bunch of Xs in it but position function doesn't return a correct value, what's going wrong?
    private int positioni(){
           int i=0;
           int j=0;
           int b=0;
           String line="";
            while(line!= null){
                for(int a=0; a<line.length(); a++){
                    if(line.charAt(a)=='X'){
                        i=a;}
                b++;
                j=b;
                t=line.length();
                line=read(gridFileN);
           return i;
    private String read(String ggridFileN){
             TextStreamReader ggridFile = new TextStreamReader(ggridFileN);
             return ggridFile.readLine();

  • Reading a text file into a StringBuffer?

    Hey all,
    I've taken a year of Java programming class so far, but I doubt my class is ever going to get in to things like this. I've been trying to develop a program that reads a small text file into a StringBuffer for manipulation and use in the program. I've been looking around the web, but thus far all I've seen are things like FileInputStream, in the java.io.* package; nothing about StringBuffers.
    And I'm pretty sure it's kind of hard, too. If someone could give me a simple(?) explanation, or a link to a tutorial that shows you this or something, it would be much appreciated.
    Also, is it possible to pull an integer out of a string? I was just wondering this, I don't think you can cast a string to an int or anything. Ha ha.
    ~Darkslime, Java student

    Hey all,
    I've taken a year of Java programming class so far,
    but I doubt my class is ever going to get in to
    things like this. I've been trying to develop a
    program that reads a small text file into a
    StringBuffer for manipulation and use in the program.
    I've been looking around the web, but thus far all
    I've seen are things like FileInputStream, in the
    java.io.* package; nothing about StringBuffers.
    And I'm pretty sure it's kind of hard, too. If
    someone could give me a simple(?) explanation, or a
    link to a tutorial that shows you this or something,
    it would be much appreciated.
    Also, is it possible to pull an integer out of a
    string? I was just wondering this, I don't think you
    can cast a string to an int or anything. Ha ha.
    ~Darkslime, Java student
    try {
            BufferedReader in = new BufferedReader(new FileReader("infilename"));
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            in.close();
        } catch (IOException e) {
        }

  • How do you read data from a text file into a JTextArea?

    I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?

    Student_Coder wrote:
    1) Read the file messages.txt into a String
    2) Initialize messages with the String as the textSwing text components are designed to use Unix-style linefeeds (\n) as line separators. If the text file happens to use a different style, like DOS's carriage-return+linefeed (\r\n), it needs to be converted. The read() method does that, and it saves the info about the line separator style in the Document so the write() method can re-convert it.
    lethalwire wrote:
    They have 2 different ways of importing documents in this link:
    http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
    Neither of those methods applies to JTextAreas.

  • Adding data from a text file into a JTextArea

    I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?

    then you need to be more specific in what you need help with because those are two commonly used options for reading data in from a file. what have you tried? where is your code failing? what kind of errors are you getting? of course it looks like others in the forum have already reprimanded you for failing to post properly.
    i have used both FileReader and the nio package for cfg and ini files which are both just txt files as well as massive data files. so tell me how they dont help you?

  • Reading a text file into a clob

    Hi guys,
    I'm trying to read in a text file and store it in an Oracle database as a CLOB. However, I'm trying it with a 200K file and it takes ages and then produces this:
    java.sql.SQLException: Io exception: Software caused connection abort: socket write error
    Here is my code:
    conn.setAutoCommit(false);
    String query = "insert into tests (ScriptID, Test) values (?, ?)";
    PreparedStatement insertTests = conn.prepareStatement(query);
    insertTests.setInt(1, scriptID);
    insertTests.setCharacterStream(2, new java.io.FileReader(test), (int) test.length());
    insertTests.executeUpdate();
    insertTests.clearParameters();
    conn.setAutoCommit(true);I've also tried using
    insertTests.setAsciiStream(2, new java.io.FileInputStream(test), (int) test.length()); (as recommended at http://otn.oracle.com/sample_code/tech/java/codesnippet/jdbc/lob/LobToSP.html) but this produces a different exception (java.sql.SQLException: Io exception: Char array not long enough: javaCharsToUtf8Bytes)
    Any help with this problem would be greatly appreciated.
    Cheers!
    sirdavidoff

    I know there were some problems writing larger files with the thin driverI think the issue has to do with the 4k limit, anything over 4000 must be done in chunks of 4000.
    ;o)
    V.V.

  • Read a text file into a map?

    I need to create a map that looks something like this:
    temp0 -> A
    temp1 -> A
    temp2 -> B
    temp3 -> C
    temp4 -> B
    temp5 -> A
    temp6 -> C
    Now instead of implementing this in a .java file (that needs to be compiled) I was wondering if there was some way to just define the mapping in a plain text file and then read it into a map when needed.
    I know how to read tokens using the tokenizer, but are there any java tools specially made for this purpose?

    You might be interested in [the Properties class|http://java.sun.com/javase/6/docs/api/java/util/Properties.html].

  • How to read\write text file into oracle database.

    Hello,
    I am having text file called getInfo in c:\temp folder. I would like to populate data from text file to data base. How to proceed. Could anybody help me out.
    Thanks,
    Shailu

    Here is a web page with easy to follow instructions regarding external files: http://www.adp-gmbh.ch/ora/misc/ext_table.html.
    Now I understand what all the excitement is over external tables.
    "External tables can read flat files (that follow some rules) as though they were ordinary (although read-only) Oracle tables. Therefore, it is convenient to use external tables to load flat files into the DB." -from the above link.

  • Reading a text file into a program

    Hi
    First off I am new to this and know very little about Cocoa programming. I have followed some tutorials e.t.c. and can make basic applications but I have a project I am doing which requires more knowledge than I have.
    The problem: part 1
    I can make a basic 'Hello world' app that has a window and has text in it, but i want this text to be read directly from an external text file. I plan on using a heart rate monitor which will give me information via the serial port and i have written the appropriate applescript to write this data to a text file. I now want a basic cocoa application that will display the contents of this text file as to show the users heart rate.
    This is only the beginning but i figure it's a start, once i have this down i can move onto the real reason behind the project.
    Below is what i found in the ref library. I think it's what i need to be using but i don't know where to put it and where to define the text file that needs to be read.
    "stringWithContentsOfFile:encoding:error:
    Returns a string created by reading data from the file at a given path interpreted using a given encoding.
    *+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError *)error
    Parameters
    path
    A path to a file.
    enc
    The encoding of the file at path.
    error
    If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.
    Return Value
    A string created by reading data from the file named by path using the encoding, enc. If the file can’t be opened or there is an encoding error, returns nil."
    Below is my code i made using a tutorial. All it does it make a window appear with 'hello world' in it. The idea is to replace the hello world with the text in the external .txt file
    #import "HelloView.h"
    @implementation HelloView
    - (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    // Initialization code here.
    return self;
    - (void)drawRect:(NSRect)dirtyRect {
    NSString* hello = @"Hello, World!";
    NSPoint point = NSMakePoint(15, 75);
    NSMutableDictionary* font_attributes = [NSMutableDictionary new];
    NSFont* font = [NSFont fontWithName:@"Futura-MediumItalic" size:42];
    [font_attributes setObject:font forKey:NSFontAttributeName];
    [hello drawAtPoint:point withAttributes:font_attributes];
    [font_attributes release];
    @end
    If anyone can help me it would be much appreciated
    Thanks
    Adam

    Hello,
    Well doing that way you just need to put another string in the "hello" container.
    Instead of - (void)drawRect:(NSRect)dirtyRect {
    NSString* hello = @"Hello, World!";
    /...../} you define "hello" another way
    - (void)drawRect:(NSRect)dirtyRect {
    NSString *hello = [NSString stringWithContentsOfFile:@"/Your/Path/Here/" encoding:NSUTF8StringEncoding error:NULL];//Assuming UTF8 encoding
    if ( ! hello)
    hello =@"Failed to load the string";
    NSPoint point = NSMakePoint(15, 75);
    NSMutableDictionary* font_attributes = [NSMutableDictionary new];
    NSFont* font = [NSFont fontWithName:@"Futura-MediumItalic" size:42];
    [font_attributes setObject:font forKey:NSFontAttributeName];
    [hello drawAtPoint:point withAttributes:font_attributes];
    [font_attributes release];
    The "if/else" was there to test successful loading of the file, and give you hints of why in case of failure but you can do without. I changed it so you just report an error occurred to user..
    All that said drawing strings in a window is more often done using a NSTextField in Interface Builder, if you wanna learn Cocoa maybe you should go that way.

  • How to read a text file into a String?

    and also write a text file from a String. I searched the forum and found this folowing code:
    // Read and append... by Example
    try{
    String fileName = "text.txt"; // Filename
    // Make the inputfile object
    FileInputStream fi = new FileInputStream(fileName);
    byte inData[] = new byte[fi.available()];
    fi.read(inData); // Read
    fi.close(); // Close
    String text = new String(inData); // Make a textstring...
    // Now, do whatever you want with the data... and append...
    String textToAppend = "kjkjhjhKJ";
    byte outData[] = textToAppend.getBytes();
    // Make the outputfile (whith the 'append' boolean set to true
    FileOutputStream fo = new FileOutputStream(fileName,true);
    fo.write(outData);
    fo.close();
    }catch(Exception oops){}but it returns funny characters to the String from the text file and vice versa in writting the text file. Can anybody please help? Thank you.
    kindo

    See here for info on encodings:
    http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html
    Some common US encodings and common uses:
    ASCII (DOS)
    Cp1252 (Windows 9x)
    UTF8 (XML)
    import java.io.*;
    public class TextFile extends File
    private static String DEFAULT_ENCODING = "ASCII";
    private File file;
    private String encoding;
    public TextFile(File file, String encoding)
         super(file.getPath());
         this.file = file;
         this.encoding = encoding;
    public TextFile(File file)
         this(file, DEFAULT_ENCODING);
    public String load() throws Exception
         FileInputStream fis = new FileInputStream(file);
         byte[] barr = new byte[fis.available()];
         fis.read(barr);
         fis.close();
         return new String(barr, encoding);
    public void save(String str) throws Exception
         FileOutputStream fos = new FileOutputStream(file);
         fos.write(str.getBytes(encoding));
         fos.close();
    }

  • Read a text file into array

    Can anyone let me know how to get read the values column wise from the text file and put each column in each arrays.
    for eg: if we have 4 columns in the text file then the values will be stored in 4 arrays.
    Thanks in advance
    Regards
    Kutty

    Use a two dimensional array to store your data, and use the StringTokenizer class to split up the lines as you read them in from the file.

  • Reading in text file into strings

    Hi,
    I'm new to the reading in data part of java and I can't work out a good way to read in a .txt file and then store each line of the txt file into strings.
    I think I'm probably just missing something obvious but if anyone can help :D!
    Thanks,
    Bex

    Look up Scanner in Java 1.5, or BufferedReader in Java 1.4.

  • Is it possible to read a text file into an applet?

    I have a text file that contains data I want to use in my applet. Is there a way to read in the data?
    Thanks,
    Brad

    With a signed applet you can read a file from the local hard disk. There is a forum for signed applets. The source code of your signed applet will require some additional code (before opening and reading the file, like // create a permission object
    FilePermission perm = new FilePermission("path/file", read);
    // check the permission object
    AccessController.checkPermission(perm);

  • Why wont my buffered reader insert text files into my JTextPane?

    Hello,
    First off, I want to say that I am a java newbie. This is the first time I have ever worked with java, and only for about a month now. When I try running this, nothing gets inserted into my JTextPane, and I get a java.lang.NullPointerException error. Any idea of how to fix this?
    Thanks,
    Dave
    //Set up Browse Procedure Action
            else if (e.getActionCommand().equals("Browse Procedures")){ //On a pull down menu
                      fc = new JFileChooser();
                   int result=fc.showOpenDialog(this);
                   File file = null;
                        if(result==JFileChooser.APPROVE_OPTION){
                             file=fc.getSelectedFile();
                             statArea.append("Opening: " + file.getName() + "." + newline);
                        //statArea is a JTextArea
                        String record = null;
                        int recCount = 0;
                        try {
                             FileReader fr = new FileReader(file.getPath());
                             BufferedReader br = new BufferedReader(fr);
                             record = new String();
                   while ((record = br.readLine()) != null) {
                        recCount++;
                        textArea.replaceSelection(recCount + ": " + record);
                        textArea.replaceSelection(newline);
                   } //textArea is a JTextPane.  I know replaceSelection is not the right method, but
                   //I tried it anyways
                        } catch (IOException evt) {
                             System.out.println ("IOException error!");
                             evt.printStackTrace();
                        else {
                        statArea.append("Browse command cancelled by user." + newline);
                        statArea.setCaretPosition(statArea.getDocument().getLength());
                   }     

    Nevermind, problem solved

Maybe you are looking for