Read Multi Line from External File

Greetings all,
I am building a page that has random Bible scripture on the
bottom and I have the scriptures saved in a text file and flash
pulls it from there. I am trying to get the Chapter and verse
portion of the text to be on a new line when brought in to the
page. Examples:
quote0=And the second is like it: 'Love your neighbor as
yourself'. Matthew 22:39
&quote1=And we know that in all things God works for the
good of those who love him, who have been called according to his
purpose. Romans 8:28
&quote2=Do not repay anyone evil for evil. Be careful to
do what is right in the eyes of everybody. Romans 12:17
&quote3=Humility and the fear of the LORD bring wealth
and honor and life. Proverbs 22:4
&quote4=In everything I did, I showed you that by this
kind of hard work we must help the weak, remembering the words the
Lord Jesus himself said: 'It is more blessed to give than to
receive.' Acts 20:35
&quote5=Blessed is he who has regard for the weak; the
LORD delivers him in times of trouble. Psalm 41:1
&quote6=Turn from evil and do good; then you will dwell
in the land forever. Psalm 37:27
&quote7=Worship the LORD with gladness; come before him
with joyful songs. Psalm 100:2
&quote8=The Father loves the Son and has placed
everything in his hands. John 3:35
Notice at the end of each scripture is the chapter and verse.
Is there a way to get this to automatically get created on a new
line? On some of them, it looks funny on the page because the
Chapter name will be on one line and the verse numbers on the next.
You can see an example of the output at
www.southernhospitalitycaterers.com to see what I am referring to.
I have tried \r \n and many combinations to no avail and
would appreciate any assistance.
Thanks
Wally

You could create the chapter/verse# as separate variables.
OR
You could put a special set of characters, like "xyz" to
separate them in the file and then replace it with a line return.
AS3 has the String.replace() method and AS2 has the
Textfield.replaceText() method.

Similar Messages

  • How can I input read a line from a file and output it into the screen?

    How can I input read a line from a file and output it into the screen?
    If I have a file contains html code and I only want the URL, for example, www24.brinkster.com how can I read that into the buffer and write the output into the screen that using Java?
    Any help will be appreciate!
    ======START FILE default.html ========
    <html>
    <body>
    <br><br>
    <center>
    <font size=4 face=arial color=#336699>
    <b>Welcome to a DerekTran's Website!</b><br>
    Underconstructions.... <br>
    </font> </center>
    <font size=3 face=arial color=black> <br>
    Hello,<br>
    <br>
    I've been using the PWS to run the website on NT workstation 4.0. It was working
    fine. <br>
    The URL should be as below: <br>
    http://127.0.0.1/index.htm or http://localhost/index.htm
    <p>And suddently, it stops working, it can't find the connection. I tried to figure
    out what's going on, but still <font color="#FF0000">NO CLUES</font>. Does anyone
    know what's going on? Please see the link for more.... I believe that I setup
    everything correctly and the bugs still flying in the server.... <br>
    Thank you for your help.</P>
    </font>
    <p><font size=3 face=arial color=black>PeerWebServer.doc
    <br>
    <p><font size=3 face=arial color=black>CannotFindServer.doc
    <br>
    <p><font size=3 face=arial color=black>HOSTS file is not found
    <br>
    <p><font size=3 face=arial color=black>LMHOSTS file
    <br>
    <p><font size=3 face=arial color=black>How to Setup PWS on NT
    <BR>
    <p><font size=3 face=arial color=black>Issdmin doc</BR>
    Please be patient while the document is download....</font>
    <font size=3 face=arial color=black><br>If you have any ideas please drop me a
    few words at [email protected] </font><br>
    <br>
    <br>
    </p>
    <p><!--#include file="Hits.asp"--> </p>
    </body>
    </html>
    ========= END OF FILE ===============

    Hi!
    This is a possible solution to your problem.
    import java.io.*;
    class AddressExtractor {
         public static void main(String args[]) throws IOException{
              //retrieve the commandline parameters
              String fileName = "default.html";
              if (args.length != 0)      fileName =args[0];
               else {
                   System.out.println("Usage : java AddressExtractor <htmlfile>");
                   System.exit(0);
              BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
              StreamTokenizer st = new StreamTokenizer(in);
              st.lowerCaseMode(true);
              st.wordChars('/','/'); //include '/' chars as part of token
              st.wordChars(':',':'); //include ':' chars as part of token
              st.quoteChar('\"'); //set the " quote char
              int i;
              while (st.ttype != StreamTokenizer.TT_EOF) {
                   i = st.nextToken();
                   if (st.ttype == StreamTokenizer.TT_WORD) {          
                        if (st.sval.equals("href")) {               
                             i = st.nextToken(); //the next token (assumed) is the  '=' sign
                             i = st.nextToken(); //then after it is the href value.               
                             getURL(st.sval); //retrieve address
              in.close();
         static void getURL(String s) {     
              //Check string if it has http:// and truncate if it does
              if (s.indexOf("http://") >  -1) {
                   s = s.substring(s.indexOf("http://") + 7, s.length());
              //check if not mailto: do not print otherwise
              if (s.indexOf("mailto:") != -1) return;
              //printout anything after http:// and the next '/'
              //if no '/' then print all
                   if (s.indexOf('/') > -1) {
                        System.out.println(s.substring(0, s.indexOf('/')));
                   } else System.out.println(s);
    }Hope this helps. I used static methods instead of encapsulating everyting into a class.

  • Problem while reading a line from a file

    Hi all
    I am facing a problem while readinga line from a file ,
    line contains some french characters due to which it skips sequence, returning invalid record in a variable
    e.g 'abcdefghÛLasasa'
    Starting Point of Û is 9 and if
    V1:=substr(''abcdefghÛLasasa',9,3)
    result is v1='ÛLas' which is invalid
    can i anybody help me out in resolving this problem

    Hello,
    What is your oracle version? And what is your expected result.
    I used the same string and this is my output on 10.2.
    select substr('abcdefghÛLasasa',9,3) mystring from dual;
    MYS
    ÛLa
    1 row selected.Regards
    Edited by: OrionNet on Jan 29, 2009 12:45 AM

  • How to handle multiple threads to read one line from a file each time?

    Dear Sir or Madam,
    I'm new to multiple threads java programming. What I want to do is as following:
    1. I'm writing a program to read one line of text from a very large file, and then do some process on this one line of text, then read the next line of text from this file, then process on this line of text, ...... When reach the end of the file, close the file.
    This is a single thread scenario.
    2. To fullly untilized computer resource, I want to create multiple threads to process this large file.
    One thing is very important is that each line of text in the large file has to be read sequentially. This means that the first line of text in the large file is read first, then the second line, then the third line ......
    My question is that if I create multiple threads to process the same file, how can I make sure that different threads will read the line of text from the same file sequentially?
    I don't have enough experience on java multiple threads programming, so it will be very appreaciated if you can help me on this as soon as you are available.
    Thanks and regards,
    Steven Wu

    A better solutoin would be to have a single thread that reads each line an puts it into a queue, and then multiple threads reading from the queue to process these lines.
    This will only be effective if the amount of processing to be done on each line is very large compared to how long it takes to read the line, or if you have more than one CPU on your machine.

  • How to read a line from a file which contains 45000 characters?

    Hi all,
         Iam a receiving a .CSV file which contains n number of rows ,each row has a data seperated with delimiter.
    These values based on delimiter it is seperated and certain validations are handled.
    Iam using UTL_FILE.GET_LINE operator to read the value and store it in a variable which is declared as l_text VARCHAR2(30000).
    when we receive a line which contains huge characters say 45000 then it throws an error(Unable to read the file).
    Only on rare cases we used to receive these kind of files with huge size.
    Kindly help to solve this issues.
    Database details.
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE 11.2.0.2.0 Production
    TNS for Linux: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    Hereby i have tried with long Raw data type but still same error unable to read the file.pls find the sample code below,
    declare
    l_text             LONG RAW;
    l_importTypeFile   UTL_FILE.FILE_TYPE ;
    begin
         PKG_COMMON.PROC_FOPEN(g_Directory, P_FILENAME,    'RB',l_importTypeFile,    p_error_cd, p_error_msg) ;
    UTL_FILE.GET_RAW(l_ImportTypeFile,l_Text);
    End;
    Thanks in Advance
    Siva

    Hi Siva,
    Are you trying to use data from this .csv file into your realtion tables. If yes and If you are using 11g Oracle database. I would suggest you create External Tables using the below query,
    http://www.oracle.com/technetwork/issue-archive/2011/11-mar/o21nanda-312277.html
    STEP1: You need a Directory where your SCHEMA has read/write access. Store the csv file in that directory.
    STEP2: Create an EXTERNAL Table script. Please refer the above URL. Examples are for coma delimiter (,); replace it with your pipe (|) in the code
    STEP: Once your external table is created you can simply create a relational table as below:
    CREATE  TABLE relation_table
      AS
    SELECT * FROM external_table;
    Regards,
    RaviR

  • How to read long line from text file

    Hi,
    I just faced problem when reading a big text file.
    BufferedReader br = new BufferedReader(new FileReader("D:\\afile.txt"));
    String str;
    int i;
    while ((str = br.readLine())!=null)
    i++;
    //do some work here...
    ...This code throws exception:
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceSo I thought file line is very long. When I opened it in FAR it only displays no more than 4096 characters as a line.
    Help me to read a text file that's line is very long?

    try,
    $ java -X
    -Xmixed mixed mode execution (default)
    -Xint interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
    set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
    append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
    prepend in front of bootstrap class path
    -Xnoclassgc disable class garbage collection
    -Xincgc enable incremental garbage collection
    -Xloggc:<file> log GC status to a file with time stamps
    -Xbatch disable background compilation
    -Xms<size> set initial Java heap size
    -Xmx<size> set maximum Java heap size
    -Xss<size> set java thread stack size
    -Xprof output cpu profiling data
    -Xrunhprof[:help]|[:<option>=<value>, ...]
    perform JVMPI heap, cpu, or monitor profiling
    -Xdebug enable remote debugging
    -Xfuture enable strictest checks, anticipating future default
    -Xrs reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni perform additional checks for JNI functions
    The -X options are non-standard and subject to change without notice.

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • Having trouble reading specific lines from a text file and displaying them in a listbox

    I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
    occurred in mscorlib.dll"
    Below is the code from that form. 
    Option Strict On
    Option Infer Off
    Option Explicit On
    Public Class frmInventoryReport
    Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
    Dim intTemp As Integer
    intTemp = lineNumber
    Return lines(lineNumber - 1)
    lineNumber = intTemp
    End Function
    Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
    For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
    If fileName.ToLower().Contains(phrase.ToLower()) Then
    Return True
    End If
    Next
    Return False
    End Function
    Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim intcase As Integer = 1
    Dim strTemp, strlist, strFile As String
    Dim blnCheck As Boolean = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Do While blnCheck = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
    Dim allLines As List(Of String) = New List(Of String)
    Do While objReader.Peek <> -1
    allLines.Add(objReader.ReadLine())
    Loop
    objReader.Close()
    strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
    lstInventory.Items.Add(strlist)
    intcase += 1
    strTemp = intcase.ToString
    strFile = "Report Q" & intcase.ToString & ".txt"
    blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
    Loop
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim intcase As Integer = 1
    Dim strTemp, strlist, strFile As String
    Dim blnCheck As Boolean = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Do While blnCheck = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
    Dim allLines As List(Of String) = New List(Of String)
    Do While objReader.Peek <> -1
    allLines.Add(objReader.ReadLine())
    Loop
    objReader.Close()
    strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
    lstInventory.Items.Add(strlist)
    intcase += 1
    strTemp = intcase.ToString
    strFile = "Report Q" & intcase.ToString & ".txt"
    blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
    Loop
    End Sub
    End Class
    Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!

    Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
    Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it.  Is there anything other than name and cage number that should be associated with each animal?
    You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple.  Here's a simple class example:
    Public Class Animal
    Public Property Name As String
    Public Property Cage As String
    Public Overrides Function ToString() As String
    Return String.Format("{0} - {1}", Name, Cage)
    End Function
    End Class
    With that you can use a routine like the following to loop through all of the files and read each one:
    Dim animals As New List(Of Animal)
    Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
    For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
    Using reader As New System.IO.StreamReader(filePath)
    Dim lineIndex As Integer = 0
    Dim currentAnimal As New Animal
    While Not reader.EndOfStream
    Dim line As String = reader.ReadLine
    If lineIndex = 0 Then
    currentAnimal.Name = line
    ElseIf lineIndex = 22 Then
    currentAnimal.Cage = line
    Exit While
    End If
    lineIndex += 1
    End While
    animals.Add(currentAnimal)
    End Using
    Next
    'do something to display the animals list
    Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView.  If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
    There are lots of options depending on what you want and what all you need to do.
    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

  • Dynamic Internal Table for reading data from external file

    Hello All,
    The task was to create a internal table with dynamic columns,
    Actually this is my first task in the WebAS 6.20, my program is based on input file provided by user with certain effort. this file can have different effort for a one yr to five year frame..
    I needed to read the raw data from file, based on months create a internal table to hold the data, after this i need to validate the data...
    I have browsed thru dynamic internal table topic, but couldn't find any dynamic appending structure, the dynamic structure would contains 12 month fileds.
    can any one help me in getting my task completed..
    Thanks
    Kumar

    Hi,
    I see that you posted the same question a couple of days ago at Dynamic Internal Table for reading data from external file Didn't Charles's response address your problem?
    Regards

  • Read & write from external files in java

    Hello everybody,
    I need your help in two problems. I have to write a method that read specific numbers from a file, save them in an array, do some calculation on that array and write it again in a new file.
    For example, I have a file that contains the following:
    #VRML V1.0 ascii
    Material {
    diffuseColor [ 1 1 1 ]
    ShapeHints {
    vertexOrdering COUNTERCLOCKWISE
    shapeType UNKNOWN_SHAPE_TYPE
    Coordinate3 {
    point [
              1 0 0 ,
              1 1 0 ,
              1 1 1 ,
              1 0 1 ,
              0 1 0 ,
              0 1 1 ,
              0 0 1 ,
              0 0 0 ,
    IndexedFaceSet {
    coordIndex [
    0,1,2,-1,
    0,2,3,-1,
    1,4,5,-1,
    1,5,2,-1,
    3,2,5,-1,
    3,5,6,-1,
    0,3,6,-1,
    0,6,7,-1,
    6,5,7,-1,
    7,5,4,-1,
    0,7,4,-1,
    0,4,1,-1,
    I need to read the point coordinates only and save them in a two dimension array, then I'll do some transformation on that array and write it in a new file that contains the previous data but the point coordinates are the transformed coordinates. I tried the following:
    FileReader in = new FileReader("C:\\hexahedron.txt");
              BufferedReader br = new BufferedReader(in);
              String line;
              StringTokenizer s;
              int [][] point = new int [8][3];
              int row = 0;
              int column;
              while ( (line = br.readLine()) != null) {
                   s = new StringTokenizer(line);
                   column = 0;
                   while (s.hasMoreTokens()) {
                        if ( s.nextToken() == "[" ){
                             point [row][column++] = Integer.parseInt(s.nextToken());
                   row++;
              br.close();
              in.close();
    But when I tried it, I found out that it saves 0s in the array!
    As I mentioned before, my problem is that I don't know how to read specific information from a file. I know how to write new information a file, but how to write a file that I already have with changed specific information.
    I'll be grateful if you show me how to solve those problems.
    And I hope that I explained my problems in an understandable and clear way.
    Regards,

    if ( s.nextToken() == "[" ){should beif (s.nextToken().equals("["){Also, you have two nextToken for each has hasMoreTokens, which is going to cause an exception.
    You are never hitting the parseInt code because of your equals/== error. Therefore, everything is zeros.
    The order of reading lines and checking for "[" isn't right. You should find the [ (maybe including the "point" word), then get numbers from the following lines (read line, tokenize, read line, tokenize, ...) until you hit the end of the points.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Read lines from a file

    With "ApartmentFileHandler" I can write Apartment-objects to a file and read them from a file.
    To write I loop through each room in the apartment and write its size
    and type. I put 1 Room per line.
    To read I read each line of the file and recreate the room stored
    there. When there are no lines left in the file I pass the Rooms from
    the file to the Apartment constructor and return the new Apartment.
    Only one Apartment is stored in each file. (Apartment doesn?t implement
    Serializable, so I cant write straight Apartment-objects to a file.)
    So in the file, there are stored one "Room" per line: String type,
    double size
    QUESTION: How am I able to read all lines: first line first -> make a new room of
    it, and store to a roomArray? Then second -> do same as I did to the
    first.
    Now my read()-method doesn't read all lines. How to change it to read next line?
    Thanks in advance.
    public class Room extends Space
    public Room(String type, double area)
    public String getType()
    public double getSize()
    public class Apartment extends Space
    public static final String KITCHEN
    public Apartment(Room[] rooms)
    public String getType()
    public double getSize()
    public Room[] getRooms()
    public class ApartmentFileHandler extends Object {
         private FileOutputStream ostream;
         private ObjectOutputStream op;
         private FileInputStream istream;
         private ObjectInputStream ip;
         private String filepath;
    public ApartmentFileHandler (String filepath) {
                              this.filepath = filepath;      
    public Apartment read()
                                      throws InvalidApartmentFile,
                                                 IOException {
          istream = new FileInputStream(filepath);
          ip = new ObjectInputStream(istream);
                                  // count how many rows in the file ie. rooms
                           String lineThatIsRead = ip.readLine();
                           int count =0;                                             
                           while (lineThatIsRead != null) {
                                    count =count +1;
                                    lineThatIsRead =ip.readLine();
         Room room;
         Room roomArray[ ] = new Room[count];
          for(int i =0; i<count; i++) {
                                  String type  =ip.readUTF();
              double size =ip.readDouble();
                                   room =new Room(type, size);
              roomArray[ i ] =room;
                                Apartment apartment = new Apartment(roomArray);
                                return apartment;
            public void write(Apartment apartment)
                  throws IOException {
                    ostream = new FileOutputStream(filepath);
                    op = new ObjectOutputStream(ostream);
                    int numberOfRooms =apartment.getRooms().length;
                    Room[] allRooms =apartment.getRooms();
                    for (int i=0; i< numberOfRooms; i++) {
                         op.writeUTF( allRooms[ i ].getType() );
                         op.writeDouble( allRooms[ i ].getSize() );
                         op.writeChars("\n");

    Hi,
    I recommend using java.io.BufferedReader in conjunction with java.io.FileReader:
    BufferedReader reader=new BufferedReader(new FileReader(filepath));
    java.io.BufferedReader provides the method public java.lang.String readLine() throws java.io.IOException which lets you read a complete line from the underlying java.io.Reader object. Furthermore, BufferedReader will - as the name implies - buffer your IO-operations which will help you improve the program's performance. In order to read all the lines contained in a text file you might want to apply a loop:
    String line;
    while((line=reader.readLine())!=null && line.length()!=0){
    //process data in string line (parse into string and double)
    Of course, everything must be contained within a try-catch-block in order to be able to handle upcoming IOException objects.
    Regards,
    Michael

  • Read lines from text file to java prog

    how can I read lines from input file to java prog ?
    I need to read from input text file, line after line
    10x !

    If you search in THIS forum with e.g. read lines from file, you will find answers like this one:
    Hi ! This is the answer for your query. This program prints as the output itself reading line by line.......
    import java.io.*;
    public class readfromfile
    public static void main(String a[])
    if you search in THIS forum, with e.g. read lines from text file
    try{
    BufferedReader br = new BufferedReader(new FileReader(new File("readfromfile.java")));
    while(br.readLine() != null)
    System.out.println(" line read :"+br.readLine());
    }catch(Exception e)
    e.printStackTrace();
    }

Maybe you are looking for

  • Officejet 7310xi All in One Printer no longer connects wirelessly

    Hello all, My Officejet 7310xi All in One Printer no longer connects wirelessly. The printer does no show up while searching for it wirelessly where it had previously. In the past it would say that the printer (HP Series 7300) was offline.  I would r

  • PC webcam works on Mac, but not on Toshiba P35...?

    I recently got the Logitech Quickcam Communicate Deluxe webcam, which is made to work with Windows XP & Vista computers. Without installing a thing, I plugged it in to my Mac (running Tiger 10.4.11) - and it works flawlessly (the camera is Video Clas

  • Iphone 6 vs iphone 6 plus screen resolution big difference?

    Hi i wanted to ask you guys if the resolution is a big difference between 326ppi (6) vs 401ppi (6+) i mean do you see the difference when holding the iphone at normal range? or do you only see the difference if you bring the phone up to your nose? th

  • How develop INCLUDE ZXMRMU01 in standard function 'EXIT_SAPLBARM_001'.

    Hi all, now in standard have function: EXIT_SAPLBARM_001 i want develop INCLUDE ZXMRMU01 . when i double click INCLUDE ZXMRMU01 have warring 'Program names ZX... are reserved for includes of exit function groups' how i create or develop  INCLUDE ZXMR

  • Intra company / different business area service jobs flow

    Dear all The business process is below The Machinary plant which is providing the repair/services to its parent plant. All the incoming materils from parents plant will be non valuated for repairing thro notification. After receipt of the services ,m