Reading text files in Java 1.4.2

The program I've been working on for the past few weeks was written using the newest version of java, but I just found out yesterday that it has to be run with Java 1.4.2_10. Almost everything converted fine, my only problem being reading in a text file.
Before I used a Scanner to read each line in a text file and store it in a String array, but with Scanners unavailable, I'm completely lost. Any suggestions?
Here's my code for reading the file in, if this is at all helpful:
Scanner input=new Scanner(new File(fileName));
int counter=0;
while ((input.hasNext())&&(counter<55000)) {  
     String line=input.nextLine();
     list[counter]=line;
     counter++;
}

DrLaszloJamf wrote:
t.s wrote:
Try this
try {
File toRead = new File("C://somefile.txt");
BufferedReader reader = new BufferedReader(new FileReader(toRead));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Why do people catch the FileNotFoundException exception separately?For me it's a personal preference, I don't think there is anything wrong with using just IOException. I think if that's the case, then there is nothing wrong with catching just "Exception".
Edit: ...and I'm lazy. Eclipse does that for me ;)
Edited by: t.s on Jun 18, 2008 8:19 AM

Similar Messages

  • Read Text file using Java Script

    Hi,
    I am trying to read a text file using Java Script within the webroot of MII as .HTML file. I have provided the path as below but where I am not able to open the file. Any clue to provide the relative path or any changes required on the below path ?
    var FileOpener = new ActiveXObject("Scripting.FileSystemObject");
    var FilePointer = FileOpener.OpenTextFile("E:\\usr\\sap\\MID\\J00\\j2ee\\cluster\\apps\\sap.com\\xapps~xmii~ear\\servlet_jsp\\XMII\\root\\CM\\OCTAL\\TestTV\\Test.txt", 1, true);
    FileContents = FilePointer.ReadAll(); // we can use FilePointer.ReadAll() to read all the lines
    The Error Log shows as :
    Path not found
    Regards,
    Mohamed

    Hi Mohamed,
    I tried above code after importing JQuery Library through script Tag. It worked for me . Pls check.
    Note : You can place Jquery1.xx.xx.js file in the same folder where you saved this IRPT/HTML file.
    <HTML>
    <HEAD>
        <TITLE>Your Title Here</TITLE>
        <SCRIPT type="text/javascript" src="jquery-1.9.1.js"></SCRIPT>
        <script language="javascript">
    function Read()
    $.get( "http://ldcimfb.wdf.sap.corp:50100/XMII/CM/Regression_15.0/CrossTab.txt", function( data ) {
      $(".result").html(data);
      alert(data);
    // The file content is available in this variable "data"
    </script>
    </HEAD>
    <BODY onLoad="Read()">
    </BODY>
    </HTML>

  • Read text file using Java(streamTokenizer)

    Hi, all,
    I am lost when trying to read data from a text file to a Java prgram. The text file looks like the following:
    106,62,2322,8159,1
    106,62,3658,8333,1
    106,62,4215,8334,2
    Each number is seperated by "," and each line representing one row of data. I was thinking about using streamTokenizer to read the data into a multi-dimentional array. Since I am new to Java and just read something about the streamTokenizer from book, I would like to get some help from someone who is more experienced with that.
    Thanks for your help!
    Kevin

    Hi Kevin,
    try this:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringTokenizer;
    public class Answer {
            public static void main(String[] args) {
            List data = new ArrayList();
            try {
                BufferedReader in = new BufferedReader(new FileReader("...your text file ..."));
                String line;
                // reading the file line by line
                while ((line = in.readLine()) != null) {
                    // splitting the line into token
                    StringTokenizer st = new StringTokenizer(line, ",");
                    List row = new ArrayList();
                    while (st.hasMoreTokens()) {
                        row.add(new Integer(st.nextToken()));
                    data.add(row); // adding the row of data
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            // test result
            System.out.println(data);
    }I don't like to use arrays, because when I start reading the file, I don't know yet, how many rows of data it is containing. Therefore a java.util.List is much more convenient (you don't have to initialize). Your result is now a java.util.List containing elements of java.util.List containig elements of Integer.
    Harri

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

  • How to print a text file using Java

    How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
    THanks,.

    Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
    private void printReport()
         Frame tempFrame = new Frame(getName());
         PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
         Graphics g = printerJob.getGraphics();
                    //I wrote the method below for calculations
         printBasics(g);
         g.dispose();
         printerJob.end();
    }This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
    Ciao

  • How To Read RTF file in JAVA?  Using  iText?

    How To Read RTF file in JAVA?  Using  iText?.....
    import java.io.*;
    import com.lowagie.text.*;
    import com.lowagie.text.rtf.*;
    public class RTF3 {
    public static void main(String[] args) {
    // System.out.println("This example generate a RTF file name Sample.rtf");
    // Create Document object
    Document myDoc = new Document();
    try {
    // Create writer to listen document object
    // and directs RTF Stream to the file Sample.rtf
    RtfWriter2.getInstance(myDoc, new FileOutputStream("Sample.rtf"));
    // open the document object
    myDoc.open();
    // Create a paragraph
         Paragraph p = new Paragraph();
         p.add("Helloworld in Rtf file..amazing isn't");
         // Add the paragraph to document object
    myDoc.add(p);
    catch(Exception e) {
    System.out.println(e);
    //close the document
    myDoc.close();
    Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.width()F
         at com.lowagie.text.rtf.document.RtfPageSetting.rectEquals(RtfPageSetting.java:433)
         at com.lowagie.text.rtf.document.RtfPageSetting.guessFormat(RtfPageSetting.java:362)
         at com.lowagie.text.rtf.document.RtfPageSetting.setPageSize(RtfPageSetting.java:341)
         at com.lowagie.text.rtf.RtfWriter2.setPageSize(RtfWriter2.java:248)
         at com.lowagie.text.Document.open(Unknown Source)
         at view.RTF3.main(RTF3.java:23)
    CAN you HELP me?

    import com.lowagie.text.Document;
    import com.lowagie.text.rtf.parser.RtfParser;
    import java.io.FileInputStream;
    String inputFile = "sample.rtf";
    Document document = new Document();
    document.open();
    RtfParser parser = new RtfParser(null);
    parser.convertRtfDocument(new FileInputStream(inputFile), document);

  • How to get the source code of an HTML page in Text file Through java?

    How to get the source code of an HTML page in Text file Through java?
    I am coding an application.one module of that application is given below:
    The first part of the application is to connect our application to the existing HTML form.
    This module would make a connection with the HTML page. The HTML page contains the coding for the Form with various elements. The form may be a simple form with one or two fields or a complex one like the form for registering for a new Bank Account or new email account.
    The module will first connect through the HTML page and will fetch the HTML code into a Text File so that the code can be further processed.
    Could any body provide coding hint for that

    You're welcome. How about awarding them duke stars?
    edit: cheers!

  • How to replace a line ina text file using java?

    Hi ALL,
    Does anybody know how to replace a line in a text file uisng java.

    use this thing:
    http://doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
    open the file,
    read its contents, replace the text you need in the contents, set the contents back into the file.
    it takes care of the IO for you.

  • How to convert a HTML files into a text file using Java

    Hi guys...!
    I was wondering if there is a way to convert a HTML file into a text file using java programing language. Likewise I would also like to know if there is a way to convert any type of file (excel, power point, and word) into text using java.
    By the way, I really appreciated the help that you guys gave me on my previous topic on how to extract tests from a pdf file.
    Thank you....

    HTML files are already text files. What do you mean you want to convert them?
    I think if you search the web, you can find things for converting those MS Office files to text (or extracting text from them, as I assume you mean).

  • Reading PDF files in java

    Hi,
    can any one help me on how to read pdf files in java using itext. I have written some piece of code but it is of no use. It is giving some garbage.
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import com.lowagie.text.pdf.PdfReader;
    public class PdfAccess
    public static void main(String[] args)
    try {
    String pdfFile = args[0];
    PdfReader reader = new PdfReader(pdfFile);
    int pageCount = reader.getNumberOfPages();
    System.out.println(pageCount);
    String content = " ";
    for(int i=1;i<=pageCount;i++) {
    byte[] pageContent = reader.getPageContent(i);
    content = content+(pageContent.toString());
    System.out.println(content.trim());
    } catch(Exception e) { }
    can any one help me on how to get contents of the file. Are there examples avalilable??

    * Try this by PDFBOX , it will execute well as per ur request..........
        public void getPdfText(String fileName) throws IOException {
            StringWriter sw = new StringWriter();
            PDDocument doc = null;
            try {
                doc = PDDocument.load(fileName);
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setStartPage(1);
                stripper.setEndPage(Integer.MAX_VALUE);
                stripper.writeText(doc, sw);
                OutputStream out=new FileOutputStream(new File("d://PDFText.txt"));
                PrintStream write=new PrintStream(out,true,"UTF-8");
                write.print(sw.toString());
                //System.out.println(sw.toString());
            } finally {
                if (doc != null) {
                    doc.close();
    Can..Can...If we Try...!

  • How can I read text files from LAN if I only know the hostname?

    I'm new in Java Developing, and dont know the written classes yet. I need help, how to do the following steps?
    <p>1. How can I read text files from LAN if I only know the hostname, or IP address?
    <p>2. How to read lines from text files without read all lines from the beginning of file, just seek to a position.
    (ex. how can I read the 120th line?)
    <p>Please help!
    <p>sorry for the bad english

    I'm new in Java Developing, and dont know the written classes yet. I need help, how to do the following steps?
    1. How can I read text files from LAN if I only know the hostname, or IP address?You need to know the URL of the file. You need to know the hostname, port, protocl and relative path.
    The hostname is server, not file.
    2. How to read lines from text files without read all lines from the beginning of file, just seek to a position.Use the seek() to get to a random byte.
    (ex. how can I read the 120th line?)The only way to find the 120th line is to read the first 120 lines. You can use other file formats to find the 120th line without reading the whole file but to need to be able to detremine where the 120th line is

  • Can I save and read text files on a server that I host?

    Hello everyone,
    I am a java hobbiest. I was wondering if I set up my own server, running out of my house, could I have my applets save to my computer and read from my computer without having to learn JDBC and a DATABASE language. In other words could i just have my applet save and read text files from and to my server?
    I'm trying to set up a sight for my 5th grade class where parents can log into. Thanks for your time.
    Oh yeah, which is easier, learning how to set up a server or learning JDBC and a DATABASE language?
    If you have any other good idease please tell me them
    Thank you, Bryan

    Short answer: This isn't gonna work
    Long answer: For this to work, the first thing you're going to need is a static IP address and a DNS name registered -actually you don't necessarily need #2 but you're probably gonna want it and it's by far the easier of the steps.
    As far as I know to get a fixed IP address you've either gotta be directly attached to a larger network (ie university network) or get a leased line from an ISP.
    Once you've got that done come back to us.

  • Reading text files without specifying the encoding?

    I have looked everywhere for a solution, but I can't find one. The problem is that I'm using codes that everybody is using, but for some reason, my codes aren't working.
    I want to be able to open up text files in Java without having to specify the encoding for the files that I'm going read, because I have no idea which encoding they will use.
    But even when specifying UTF-8 to be encoding of the file to read, it doesn't work correctly:
    FileInputStream fileIS= new FileInputStream("somefile.txt");
    Reader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
    EVERYWHERE I look, ppl are using these codes! But it doesn't work, some characters (such as the Euro sign) are displayed as squares.
    However, I want to be able to read not only UTF-8 files but anything that Java supports. Any ideas?
    Edited by: Stalfos on Oct 22, 2007 12:22 PM

    Stalfos wrote:
    I want to be able to open up text files in Java without having to specify the encoding for the files that I'm going read, because I have no idea which encoding they will use.
    This is your problem. If you don't know what encoding the text is stored in, then the chances that the default encoding used to read it will be correct are slim.
    But even when specifying UTF-8 to be encoding of the file to read, it doesn't work correctly:There are many different character encodings, and most of them don't overlap. Anything above 127 usually causes problems.
    FileInputStream fileIS= new FileInputStream("somefile.txt");
    Reader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
    EVERYWHERE I look, ppl are using these codes! But it doesn't work, some characters (such as the Euro sign) are displayed as squares.The problem isn't with the code, it's that the file you're reading isn't using an encoding that's compatible with UTF-8. Assuming that using UTF-8 should work for all encodings is like assuming that someone who can read Chinese should be able to read a book written in Spanish or Greek. It doesn't work that way.
    However, I want to be able to read not only UTF-8 files but anything that Java supports. Any ideas?You need to know what encoding your files are stored in, period. There are a few ways to guess what the encoding is, but they're only reliable for a small set of encodings.
    You don't seem to truly understand what character encodings are, or how to use them, so read this:
    The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
    http://www.joelonsoftware.com/articles/Unicode.html

  • If possible 2 read text files in nokia 6070 mobile...

    i have nokia 6070 mobile.i want 2 save & read my text files.if possible 2 read text files in nokia6070 mobile?

    Yes it is possible by installing a java based app.
    You can find some here.

Maybe you are looking for

  • Slow system boot with wireless keyboard

    I have a new Mac Book Pro with OS X Lion. Attached I have a Thunderbolt display, magic mouse and Apple wireless keyboard. My system just runs perfect, but sometimes it uses a long time to boot. Today I've found out that it only happens, when I first

  • How to mount an url with variable data?

    Hello fellas, i need to use a variable url in an a tag to send emails. Something like: <a href="exemple.com?guest=Name%20Of%20My%20Guest"> Anyone knows how i can encodeURI of an variable data in Eloqua??? Thanks for attention. Respect!

  • Fonts not appearing in illustrator after installing

    I am installing fonts in windows 7 by right clicking on the file and clicking install.  After successfully installing the fonts, they aren't showing up in illustrator (or photoshop).  I checked my windows font folder and the new fonts are indeed ther

  • Scaling laptop to large monitor

    hey there, i'm working off of my laptop and hooking it up to my 30" monitor. the stuff looks proportioned on laptop; but when dragged onto the larger monitor, every thing is too large. where can i scale this? went into sysetmt preferences as well as

  • Grant select permission

    As user "A" I want to grant select permissions to all my tables to user "B". Is there a way to do this in 1 command, or do I need to specify 1 table at a time.