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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Unable to create file using java.io.File

    I have attached my code
    public boolean validateZip(MultipartFile file, List<String> files) throws Exception {
              String fileName = file.getOriginalFilename();
              File tempFile = new File("C://workspace//tempData//" + fileName);
              LOG.info("Absolute path : " + tempFile.getAbsolutePath());
              ZipFile zipFile = new ZipFile(tempFile);
              LOG.info("No of enteries in the zip : " + zipFile.size());
              //loop through the list and check if the entry is in the zip file
         }The problem is, no exception is thrown in
    ' File tempFile = new File("C://workspace//tempData//" + fileName);
    but, a FileNotFoundException is thrown in
      ZipFile zipFile = new ZipFile(tempFile);Also, it specifies the Absolute Path, but when I check there, there is no file created.
    Any help is appreciated.
    TIA

    ok, when I debug my application for the following code :
    String dir = "C:\workspace";
    String fileName = file.getOriginalFilename();   // file is an instance of a multipart file
    File tempFile = new File(dir, fileName);
    ZipFile zipFile = new ZipFile(tempFile);it runs smooth, no issues, if I run my app, the following line throws a FileNotFoundException...
    ZipFile zipFile = new ZipFile(tempFile);

  • MySQL DB file using java

    Is there a way of creating a mySQL database file using java, a file similar to MS Access file?

    I recall a software that save files in .mysql format.
    Didn't know how these files were generated, but I am
    sure of the extension.Well that's swell.
    There is no such file used by MySQL. Further MySQL databases are not contained in a file but in fact use several files and are tied directly to tables. For each table you will have two files, one with structure and one with the data. Then for each index you will have another file.
    That's for MyISAM tables anyway (a MySQL variant of ISAM). For other table engine types it varies but multiple files per table is a common thread.
    The file you are talking about most likely contains SQL queries and is a SQL batch program for creating and populating a database.
    Anyway on to trying to actually resolve your issue. Creating ISAM files from scratch is a no-go to create a database. You can of course always connect to the database engine and issue queries like "CREATE DATABASE" or "CREATE TABLE"
    What is the actual problem you are trying to solve here?

  • Failed to delete a file in MS Vista using java.io.File.delete()

    while trying to delete a file using java.io.File.delete(), it returns true but the file lies intact.
    i'm sure there is no handle or stream open on the file..
    the same code is running fine in XP..
    if anyone can help me.. thanks

    thanks all..
    the problem is diagnosed further..
    MS Vista does not let a user program to delete any file from 'windows' or 'program files' directories..
    Even when the file is deleted manually thru explorer a confirmation is taken from the administrator.. even when he is logged in..
    i for now have opted to install and use my program in Vista outside 'program files' directory...
    more clarification welcome..

  • Running files using java

    Please help, how can i run files using java.
    Files such as installers, batch files, or exe files....
    thanx

    Dear
    To run an EXE or COM or (other types of files other than BAT) use
    Runtime.exec("program-file-name.exe");
    while for running BAT files, always use this syntax
    Runtime.exec("bat-filenane", null, "bat-file-directory");
    Thats all.
    If your directory name or filename contains spaces, then surround the directoryname + filename within double quotes.
    Regard
    Dharmendra!
    Software Engineer(Java/J2EE)

  • Write data to multiple text files after specific size

    Hello,
    I wrote a code that contineously writes data to  a text file. The problem is I am running this VI for long time and therefore this text file is being bigger in size e.g. more than 10MB. I want to split writing data in this text file after max 1MB size. Can anyone help ????
    thanks in advance.

    CMW.. wrote:
    You could use the "File/Directory Info Function" in the Advanced File VIs and Function palette to check the size. If the file is too big. close it and create a new one.
    I would use the Get File Position since this won't cause Windows to have to do so much.  Assuming you are just writing and not setting the file position manually, this will return the size of the file in bytes (file position will always be at the end of the file).
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to Write data in Excel File using java

    Hi
    can anybody help me to write data in excel file
    using java code
    Thankx In Advance

    How much are you willing to pay for that?
    If you want it for free, http://jexcelapi.sourceforge.net/

  • Error while TRANSFER System is trying to write data that were not locked

    Hi Everybody,
          I am encountering a Error Msg when i try to TRANSFER plan values .The Error masg is
    "System is trying to write data that were not locked".
    I never got this msg before. I checked my Planning query, it looks fine. I have the cells in Blue but couldn't change values or create new records.
    I have the locks set up in RSPLSE too.
    I am on BI-7 IP SP12.
    regards,
    Roger

    Hi ,
      Below is the reply i got from SAP this morning... i have asked my basis team to apply the note.. will update after i test my layout.
    *************Reply from SAP *********************
    I was able to replicate the issue in your system.
    Please implement the note 1153756 in your system.
    1153756 : Template: BI 7.0 (SP18) / BI 7.1 SPS06
    This note will solve your issue.
    If the issue still persists then , please try using a blank value for
    RSADMIN parameter RSPLS_DATA_CHECK_WRITE = X.
    This parameter triggers some 'extra' checks.
    Using a blank value should avoid these error message which you are
    getting.
    regards,
    roger

  • 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

  • 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);
    }

  • 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 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 write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • How to Write in bold to a file using java I/O classes?

    Hi,
    Using I/O classes I want to prepare a .doc file in which some text will be there. I want that text to be formatted. Like some text I want to be bold. Some text to be italic. How can I write bold/Italic text to the file using java I/O classes.
    Thanks
    Prashant

    By .doc file, I'm assuming you mean an MS Word document, yes? (fyi, Word Perfect also used the .doc extension)
    The .doc format is proprietary to Microsoft and isn't documented by them. In order to output a file in .doc format you'd have to understand that format correctly, otherwise MS Word will spit out it's tongue at you, call you names, and maybe send the Microsoft Police to "audit" your PC Software Licensing.
    Fortunately for you there is an open source project to demangle the microsoft file formats. See http://jakarta.apache.org/poi/ and especially pay attention to the HDF project (Horrible Document Format).
    - David

Maybe you are looking for