Writing Text Files in Java

hello!
i am creating an Applet game and I would like to create Rankings.
So, i need to take data from java and transfer them into HTML. At my
university's book says that everytime we open a file to write in it, if there are
already data, Java removes them and then writes the new ones. But I want
a static file where Java can write the updated rankings and HTML can take
them and use them in site. Is there any way to achive that guys?
If i wasn't clear, i just want a way to make Java not to delete any data in a file
everytime it needs to write something in it!
thanks alot!

hello!
i am creating an Applet game and I would like to
create Rankings.
So, i need to take data from java and transfer them
into HTML. At my
university's book says that everytime we open a file
to write in it, if there are
already data, Java removes them and then writes the
new ones. But I want
a static file where Java can write the updated
rankings and HTML can take
them and use them in site. Is there any way to achive
that guys?
If i wasn't clear, i just want a way to make Java not
to delete any data in a file
everytime it needs to write something in it!
thanks alot!There are a number of problems here.
First of all you can always append to a file, but that's not actually what you want to do.
Second you can read the whole file in, find the values you want, change them and write the whole file back. This is more of what you want to do but HTML is not the best choice for doing this.
But the most fundamental problem is that you do not write to files of any kind in an Applet.

Similar Messages

  • 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 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 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).

  • 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.

  • 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>

  • Changing HTML to text file using java

    Hi,
    I am doing a project in which i have to read news articles from websites. I have tried XML but for that i need to know which tag has the article in it. Since i have to read from various websites so each site used different tags for different informations.
    Is there anyway that i can change an HTML file into a text file using java. Maybe some command that removes all the HTML tags and gives just the information. Is there anything else that anyone would like to recommend?
    Thanx
    yafis

    Maybe something like this:
    import java.io.*;
    import java.net.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    class GetHTMLText
         public static void main(String[] args)
              throws Exception
              EditorKit kit = new HTMLEditorKit();
              Document doc = kit.createDefaultDocument();
              // The Document class does not yet handle charset's properly.
              doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
              // Create a reader on the HTML content.
              Reader rd = getReader(args[0]);
              // Parse the HTML.
              kit.read(rd, doc, 0);
              //  The HTML text is now stored in the document
              System.out.println( doc.getText(0, doc.getLength()) );
         // Returns a reader on the HTML data. If 'uri' begins
         // with "http:", it's treated as a URL; otherwise,
         // it's assumed to be a local filename.
         static Reader getReader(String uri)
              throws IOException
              // Retrieve from Internet.
              if (uri.startsWith("http:"))
                   URLConnection conn = new URL(uri).openConnection();
                   return new InputStreamReader(conn.getInputStream());
              // Retrieve from file.
              else
                   return new FileReader(uri);
    }

  • Writing or modifying text files in java

    Dear all,
    I have the next text file:
    goods: 5
    bids: 4
    % num, price, good, good, ..., good, #
    0 2075 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    I have to modify or create the file above, using output data from one java program. For example, The output of my java program in the next execution is:
    goods: 8
    and price (0) changes from 2075 to 2078.
    so, using this output data my java program should write (create or modify) the next text file with the changes:
    goods: 8
    bids: 4
    % num, price, good, good, ..., good, #
    0 2078 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    I have tried using: output.write( objetc );
    but it doesn't work as I need :( .
    Somebody can help me or give me some idea?
    Thanks,
    Andrea

    This is the code:
    File testFile = new File("D:\\result1.txt");
    setContents(testFile, " bla bla bla (few characters) ");
    static public void setContents(File aFile, String aContents)
    throws FileNotFoundException, IOException {
    try {
    //use buffering
    output = new BufferedWriter( new FileWriter(aFile) );
    output.write( aContents );
    finally {
    //flush and close both "output" and its underlying FileWriter
    if (output != null) output.close();
    I mean, this code dont work because it let me write few characters only. I need to write the whole file:
    goods: 8
    bids: 4
    % num, price, good, good, ..., good, #
    0 2078 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    with the special characters as (#).
    Sorry, if it post is not clear.
    Thanks.

  • Fill a text file from java code

    Hello,
    I've written a java code to insert some informations in a database and
    I also want to save the same informations in text files (.txt).
    Thanks you for your suggestions or your advice of a tutorial that can help me to perform successfully this task.
    J.S.

    Writing to a file is pretty easy in Java. A simple way is to use the PrintStream class.import java.io.*;
    public class MyClass {
      public static void main(String[] arg) throws IOException {
        PrintStream ps=new PrintStream(new FileOutputStream(new File("someTextFile.txt")));
        //now use println(String) to write lines of text to the file
        ps.println("This is a line in the file");
        //always close the PrintStream when finished
        ps.close();
    }Alternatively, for a good tutorial, click the 'Tutorials' link in the left column on this page.

  • Trying to write data to a text file using java.io.File

    I am trying to create a text file and write data to it by using java.io.File and . I am using JDeveloper 10.1.3.2.0. When I try run the program I get a java.lang.NullPointerException error. Here is the snippet of code that I believe is calling the class that's causing the problem:
    String fpath = "/test.html";
    FileOutputStream out = new FileOutputStream(fpath);
    PrintStream pout = new PrintStream(out);
    Do I need to add additional locations for source files or am I doing something wrong? Any suggestions would be appreciated.
    Thank you.

    Hi dhartle,
    May be that can help:
    * Class assuming handling logs and connections to the Oracle database
    * @author Fabre tristan
    * @version 1.0 03/12/07
    public class Log {
        private String fileName;
         * Constructor for the log
        public Log(String name) {
            fileName = name;
         * Write a new line into a log from the line passed as parameter and the system date
         * @param   line    The line to write into the log
        public void lineWriter(String line) {
            try {
                FileWriter f = new FileWriter(fileName, true);
                BufferedWriter bf = new BufferedWriter(f);
                Calendar c = Calendar.getInstance();
                Date now = c.getTime();
                String dateLog =
                    DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM,
                                                   Locale.FRANCE).format(now);
                bf.write("[" + dateLog + "] :" + line);
                bf.newLine();
                bf.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
         * Write a new line into a log from the line passed as parameter,
         * an header and the system date
         * @param   header  The header to write into the log
         * @param   info    The line to write into the log
        public void lineWriter(String header, String info) {
            lineWriter(header + " > " + info);
         * Write a new long number as line into a log from the line 
         * passed as parameter, an header and the system date
         * @param   header  The header to write into the log
         * @param   info    The line to write into the log
        public void lineWriter(String header, Long info) {
            lineWriter(header + " > " + info);
         * Enable to create folders needed to correspond with the path proposed
         * @param   location    The path into which writing the log
         * @param   name        The name for the new log
         * @return  Log         Return a new log corresponding to the proposed location
        public static Log myLogCreation(String location, String name) {
            boolean exists = (new File(location)).exists();
            if (!exists) {
                (new File(location)).mkdirs();
            Log myLog = new Log(location + name);
            return myLog;
         * Enable to create the connection to the DB
         * @return  Connection  Return a new connection to the Oracle database
        public static Connection oracleConnectionCreation() throws Exception {
            // Register the Oracle JDBC driver
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            //connecting to the DB
            Connection conn =
                DriverManager.getConnection("jdbc:oracle:thin:@myComputerIP:1521:myDB","user", "password");
            return conn;
         * This main is used for testing purposes
        public static void main(String[] args) {
            Log myLog =
                Log.myLogCreation("c:/Migration Logs/", "Test_LinksToMethod.log");
            String directory = "E:\\Blob\\Enalapril_LC-MS%MS_MS%MS_Solid Phase Extraction_Plasma_Enalaprilat_ERROR_BLOB_test";
            myLog.lineWriter(directory);
            System.out.println(directory);
    [pre]
    This class contained some other functions i've deleted, but i think it still works.
    That enables to create a log (.txt file) that you can fill line by line.
    Each line start by the current system date. This class was used in swing application, but could work in a web app.
    Regards,
    Tif                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sorting Names in a text file using java program

    h1. Deleting numbers in a text file, sorting the names  and writing in to a new file
    h2. Sample data
    =================
    71234 RAJA
    89763 KING
    89877 QUEEN
    ==================
    h2. Java Program
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.io.Writer;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    class Sortnames { 
    public static void main(String args[]) { 
    try { 
    ArrayList storeWordList = new ArrayList();
    ArrayList storeWordList2 = new ArrayList();
                   int i;
    char c;
                   String inputfile = "names_konda.txt";
                   String tempfile = "newdatafile.txt";
                   String outputfile = "sortedoutput.txt";
                   StringBuffer strBuff=null;
    Writer output = null;
    File file =null;
                   Writer sortedoutput = null;
    boolean select =false;
                   //*********************************************** Reading data from Input file     
    FileInputStream fstream = new FileInputStream(inputfile);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null) { 
    storeWordList.add(strLine);
    //Close the input stream
    in.close();
                   //*********************************************** Adding only alphabets to buffer and writing to file
                   file= new File(tempfile);
                   output = new BufferedWriter(new FileWriter(file));
    strBuff = new StringBuffer();
    for (Iterator iter = storeWordList.iterator(); iter.hasNext();) { 
         String s = (String) iter.next();
                        //System.out.println("String "+s);
         for (i = 0; i < s.length() ; i++)
    c = s.charAt(i);
    if (Character.isLetter(c)) {
    strBuff.append(c);
                        strBuff.append("\n");
    String myout = strBuff.toString();                
         output.write(myout);
         output.close();
         //============================================== Reading the created file,Sorting and placing in Collections
                   FileInputStream fstream2 = new FileInputStream(tempfile);
    // Get the object of DataInputStream
    DataInputStream in2 = new DataInputStream(fstream2);
    BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
    String strLine2;
    //Read File Line By Line
    while ((strLine2 = br2.readLine()) != null) {                 
    storeWordList2.add(strLine2);
    Collections.sort(storeWordList2);
                   //===================================================
    File sortedfile = new File(outputfile);
    sortedoutput = new BufferedWriter(new FileWriter(sortedfile));
    for(int m=0; m<storeWordList2.size(); m++)
         if (storeWordList2.get(m).toString().trim().length() > 0)
              sortedoutput.write(storeWordList2.get(m).toString());
                        sortedoutput.write("\n");     
    sortedoutput.close();
    System.out.println("Names Sorted SUCCESFULLY");
    br.close();
    br2.close();
    in.close();
    fstream.close();
    fstream2.close();
                   ///==========================================
                   File f1 = new File(tempfile);
                   boolean success = f1.delete();
                   if (!success){
                        System.out.println("failed deletion ");
                        System.exit(0);
                        }else{
                        System.out.println("deleted");
                   // ==========================================
    } catch (Exception e) {//Catch exception if any 
    System.out.println("Error: " + e);
    h2. Thanks and regards
    h1. BalaNagaRaju.M
    h1. [email protected]

    Do you have a question? Also see the sticky welcome post on how to post formatted code.

  • 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

  • Can't read a text file using java

    Hi All
    I am trying to read a log file.
    ProgramA keeps updating the log file, while my program ProgramB reads it.
    For some readson my ProgramB is not able to read the last two lines in the log file. If I run the program in debug mode it is reading all the lines.
    This is having me frustrated.
    Please let me know if there is a way to read entire contents.
    Here is how I am reading the files ( 2ways)
         private static String readFileAsString(String filePath)
        throws java.io.IOException{
            StringBuffer fileData = new StringBuffer(1000);
            FileReader fr = new FileReader(filePath);
            BufferedReader reader = new BufferedReader(fr);
            char[] buf = new char[1024];
            int numRead=0;
            while((numRead=reader.read(buf)) != -1){
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            reader.close();
            fr.close();
            return fileData.toString();
           * Fetch the entire contents of a text file, and return it in a String.
           * This style of implementation does not throw Exceptions to the caller.
           * @param aFile is a file which already exists and can be read.
           static public String readFileAsString(String filePath) {
             //...checks on aFile are elided
             StringBuffer contents = new StringBuffer();
             //declared here only to make visible to finally clause
             BufferedReader input = null;
             try {
               //use buffering, reading one line at a time
               //FileReader always assumes default encoding is OK!
               input = new BufferedReader( new FileReader(filePath) );
               String line = null; //not declared within while loop
               * readLine is a bit quirky :
               * it returns the content of a line MINUS the newline.
               * it returns null only for the END of the stream.
               * it returns an empty String if two newlines appear in a row.
               while (( line = input.readLine()) != null){
                 contents.append(line);
                 contents.append(System.getProperty("line.separator"));
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
             finally {
               try {
                 if (input!= null) {
                   //flush and close both "input" and its underlying FileReader
                   input.close();
               catch (IOException ex) {
                 ex.printStackTrace();
             return contents.toString();
           }

    If you're using JDK 5 or later, you could use the Scanner class for input information. See below:
    try {
                   Scanner reader = new Scanner(new File("C:\\boot.ini"));
                   StringBuilder sb = new StringBuilder();
                   while (reader.hasNextLine()) {
                        sb.append(reader.nextLine());
                        sb.append(System.getProperty("line.separator"));
                   System.out.println(sb.toString());
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              }

Maybe you are looking for