Applet writing on a output file

I am new to JAVA and I've got jdk 1.4.1 downloaded.
I am thinking it is possible to have a JAVA applet
which writes on a output file.
In order to do that, I tried to use the code below, where the Applet "write.class" should display a string on a painted area and write to file "myfile.txt".
Now compilation is OK (no error or warning messages), and I tried to incorporate this Applet into a HTML code (by using the sintax <applet code="write.class" width=200 height=50> </applet>).
When I open the HTML document using Internet Explorer the Applet is run, but the file "myfile.txt" is not created.
Can somebody explain me what is going wrong?
Any suggestion or comment is welcome and appreciated.
import java.applet.Applet;
import java.awt.*;
import java.io.*;
public class write extends Applet {
public void paint(Graphics g) {
g.drawString("The Java Applet is Writing!",20,30);
     main();
public static void main(){ 
FileOutputStream out;
PrintStream p;
     try
          out = new FileOutputStream("myfile.txt");
p = new PrintStream( out );
          p.println ("This is to be written to a file");
p.close();
     catch (Exception e)
          System.err.println ("Error writing to file");

applets are not allowed to write to the local file system.
you wouldn't like something that came with a web site without your confirmation fill up your hard drive, would you?

Similar Messages

  • Writing to an output file

    Hello all,
        I have an ABAP program in BW which reads the data from a BW ODS active table and writes the output to an external file on the server.
        The file that is generated is huge(13 MB). The file is generated with the correct results, but along with the data, the program header(filename, path, etc) is also written to the output file which is undesirable. The header is written for every few hundred pages. I want to avoid this.
    Database is Oracle.
       The syntax for the file declaration is..
    PARAMETERS: fileout(120) type c lower case default 'xxxx.csv' 
                        obligatory.
    and the open statement is as follows....
    OPEN DATASET fileout FOR OUTPUT IN TEXT MODE ENCODING DEFUALT.
    In the above statement I want to try taking out the "ENCODING DEFAULT" clause, but it says "in TEXT MODE the ENCODING must be added". I have seen other programs which are already there without that clause.
       Any suggestions will greatly appreciated. Thanks.
    Message was edited by: Ajay

    I can't seem to re-create the problem.  You can you please post the exact code of the program, so that we may try to re-create your problem. 
    This program works fine in my WebAs 7.0  system.
    report  zrich_0001.
    data: d1(100) type c value '/usr/sap/NSP/SYS/test.txt'.
    data: begin of itab occurs 0,
          fld1(20) type c,
          fld2(20) type c,
          fld3(20) type c,
          fld4(20) type c,
          fld5(20) type c,
          fld6(20) type c,
          end of itab.
    data: wa like line of itab.
    start-of-selection.
      do 10000 times.
        wa-fld1 = sy-index.
        wa-fld2 = sy-index.
        wa-fld3 = sy-index.
        wa-fld4 = sy-index.
        wa-fld5 = sy-index.
        wa-fld6 = sy-index.
        append wa to itab.
      enddo.
      open dataset d1 for output in text mode encoding default.
      loop at itab.
        transfer itab to d1.
      endloop.
      close dataset d1.
    Regards,
    Rich HEilman

  • Powershell scripts not writing it to output file

    Hi,
    Below is my script which loops through all sites and web in a site collection and if the particular web part is added in a page, it will give the page URL and it should be written to a output file.
    function enumerateWebParts($Url)
    $webApp = Get-SPWebApplication $Url #Get WebApplication URL
    foreach($web in $webApp | Get-SPSite -Limit All | Get-SPWeb -Limit All) #foreach loop to iterate through all sites and webs of WebApplication
    if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web)) #Check if site is a publishing site
    $pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
    $pages = $pWeb.PagesList
    foreach ($item in $pages.Items)
    $fileUrl = $webUrl + "/" + $item.File.Url
    $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
    $wps = $manager.webparts
    foreach ($type in $wps) #loop through each type found $wps
    #Write-Host " type searching";
    Write-Host $type.GetType().Name;
    if ($type.GetType().Name -eq "RightMenu") #if webpart $type -like KWizCom select webpart object
    Write-Host "found";
    $wps | select-object @{Expression={$pWeb.Url};Label="Web URL"},@{Expression={$fileUrl};Label="Page URL"},DisplayTitle, IsVisible, @{Expression={$type};Label="Type"}
    Write-Host $fileUrl;
    $page=$pweb.Url+$fileUrl;
    Write-Output $page;
    else #if web is not a publishing site
    $pages = $null
    $pages = $web.Lists["Site Pages"]
    if ($pages)
    foreach ($item in $pages.Items)
    $fileUrl = $webUrl + "/" + $item.File.Url
    $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
    $wps = $manager.webparts
    foreach ($type in $wps)
    if ($type.GetType().Name -eq "RightMenu")
    $wps | select-object @{Expression={$Web.Url};Label="Web URL"},@{Expression={$fileUrl};Label="Page URL"},DisplayTitle, IsVisible, @{Expression={$type};Label="Type"}
    Write-Host $fileUrl;
    $page=$pweb.Url+$fileUrl;
    Write-Output $page;
    else
    # Write-Host “… completed processing” $web
    $row = enumerateWebParts(‘http://sptest.danfoss.net’) #call the enumerateWebParts function pass it the URL for the web application
    I run the command through D:\RightMenu.ps1 | Out-File D:\RightMenu.txt
    Aruna

    Try 
    http://stackoverflow.com/questions/10340007/exporting-powershell-output-to-text-file
    You can always redirect the output an exe to a file like so (even from cmd.exe):
    powershell c:\test.ps1 > c:\test.log
    Within PowerShell, you can also redirect individual commands to file
    but in those cases you probably want to append to the log file rather
    than overwrite it e.g.:
    $logFile = 'c:\temp\test.log'
    "Executing script $($MyInvocation.MyCommand.Path)" > $logFile
    foreach ($proc in Get-Process) {
    $proc.Name >> $logFile
    "Another log message here" >> $logFile
    If this helped you resolve your issue, please mark it Answered

  • Reports 2.5 over-writing an existing output file

    When I try to save the Reports 2.5 output to a file that already exists, the application seems to work. However, the Report Server logs indicate an error - Rep 1081 - Unable to open file ...
    When you check if the file was created, its even worse that the original file has already been deleted - (puff! ... gone).
    Am on NT4.0 as client, could this be an NT bug or am just missing something on my code?
    Hints and suggestions please.
    null

    I really appreciate your help, but I already changed the configuration to open a file path taking another ActiveX example as a reference. Here is my subVI's I used, but they are merged in LLB. I am sorry for my ignorance of how to extract all the subVI's from this file.
    Attachments:
    ExcelExamples.llb ‏62 KB

  • Output file from an applet to a server

    Hi,
    I am trying to find a way to get my applet to create an output file on the server in the directory of the applet .class file. This seems to be a problem since most classes I have tried seem to write the ouput file to the computer which is running an instance of the applet as opposed to the server which is running the applet code. If anyone knows of a library or class that can create and write to an output file on the server in the directory of the applet .class, please let me know. Thanks.
    -Etai

    Hi,
    Check out this thread.
    http://forum.java.sun.com/thread.jsp?forum=31&thread=186534
    I hope this helped.
    Regards,
    Roopasri Vittal
    Developer Technical Support
    Sun Microsystems
    http://sun.com/developers/support

  • Writing a Vector to a Output File Line by Line.

    Can anyone tell me how to write each element of the Vector on a New Line to the Output file? Right now the Output is in a String across 1 line.
    Now - � t Bowser 5 years 105 lbs.t Bowser 5 years 106 lbs.t Daisy 1 year 30 lbs.t Dog 1 yr 66 lbs.t King 6 years 77 lbs.t Nikki 5 years 68 lbs.
    Here is what I need -
    Bowser 5 years 106 lbs.
    Bowser 5 years 105 lbs.
    Rover 7 years 88 lbs.
    Dog 1 yr 66 lbs.
    King 6 years 77 lbs.
    Nikki 5 years 68 lbs.
    Daisy 1 year 30 lbs.
    Do a find on // Writes Vector Object to a file
    Thank You in advance.
    import java.io.*;
    import java.awt.*;
    import java.util.*;
    public class VectorSort
    Vector v;
    private DataInputStream inputStream = null;
    private ObjectOutputStream outputStream = null; // <== this is for a Vector
    // private DataOutputStream outputStream = null; // <== This is for a Textfile
    (1) Read in Pet Records put them in a Vector, Sort them Print them.
    public static void main(String[] args) throws java.io.IOException
    VectorSort newVector = new VectorSort();
    newVector.connectToInputFile();
    newVector.connectToOutputFile();
    newVector.readInput();
    newVector.sortPrint();
    newVector.closeFiles();
    System.out.println(" ");
    System.out.println("Check A:/DataOut.txt Now");
    public void connectToInputFile()
    String inputFileName = getFileName("Enter input file name: A://DataIn.txt");
    try
    inputStream = new DataInputStream(new FileInputStream(inputFileName));
    catch(FileNotFoundException e)
    System.out.println("File " + inputFileName + " not found.");
    System.exit(0);
    public void connectToOutputFile()
    String outputFileName = getFileName("Enter output file name: A://DataOut.txt");
    try
    outputStream = new ObjectOutputStream( // <== this is for a Vector
    // outputStream = new DataOutputStream( // <== this is for a Textfile
    new FileOutputStream(outputFileName));
    catch(IOException e)
    System.out.println("Error opening output file "
    + outputFileName);
    System.out.println(e.getMessage());
    System.exit(0);
    private String getFileName(String prompt)
    String fileName = null;
    System.out.println(prompt);
    fileName = SavitchIn.readLineWord();
    return fileName;
    //===========================================================================
    public void readInput()
    v = new Vector ();
    try
    String result = "";
    boolean done = false;
    int ctr = 0;
    String next;
    next = inputStream.readLine();
    while ( next != null)
    v.addElement( next.trim() );
    next = inputStream.readLine();
    catch(EOFException e)
    //Do nothing. This just ends the loop.
    System.out.println("Do Nothing Here");
    catch(IOException e)
    System.out.println(
    "Error: reading or writing files.");
    System.out.println(e.getMessage());
    System.exit(0);
    public void sortPrint()
    Collections.sort(v);
    int vsize = v.size();
    for (int j = 0; j < vsize - 1 ; j++)
    try
    outputStream.writeObject(v.elementAt(j)); // Writes Vector Object to a file
    System.out.println(v.elementAt(j));
    catch(IOException e)
    System.out.println("Error Writing Output "
    + e.getMessage());
    System.exit(0);
    public void closeFiles()
    try
    outputStream.flush(); // <== force the buffer to write
    inputStream.close();
    outputStream.close();
    catch(IOException e)
    System.out.println("Error closing files "
    + e.getMessage());
    System.exit(0);

    // did you try with java.io.PrintWriter
    // here is simple method to write file from vector.
    // you need to change obtaining your string value at the vector loop
    private void writeDataLog(Vector vector, String filename)
    try
    PrintWriter pw = new PrintWriter(new FileWriter(filename, true));     
    if (vector.size()>0)
    for (int i=0; i<vector.size(); i++)
    { String str = ((your object)vector.get(i)).getYourString();
    pw.println( str );
    pw.close();
    catch(Exception e)
    { System.out.print(e.toString()); }
    }

  • Applet: writing to file

    hi there.
    i need serious help on using an applet and writing the user response into a text file.
    issit possible in the first place? cos i read at a lot of sources saying applet cant write to file?
    any help is much appreciated
    thx!

    Where do you plane on writing the file to server where the applet is or on the client machine? Applets can only write to files that are on the same filesystem or on the same machine that it was loaded into the browser from. So if you want user to run this applet and have it write out a file you will have to get them to download the .class file and then run it from their computer.
    here is somthing might help a bit more.
    http://java.sun.com/sfaq/#read
    Please give more detail about what you want to.

  • What are the cases that cause the I/O error writing to output file

    may i ask what are the cases that cause the I/O error writing to output file ??
    cause i have the write path and the input file has data
    any ideas???

    and the permission is to write first time then append to itBy "permission" is meant the operating system controlled rights that let
    particular users do specified things with specified files or directories.
    the error message is a the title of the message
    I/O error writing to output fileThe java runtime actually creates a much more useful error message than
    this but, unfortunately, your program is swallowing this error message and
    replacing it with the message you see.
    Somewhere in your code you have something like:try {
        // all sorts of stuff goes here
        // including the code that is intended to
        // write to the file
    } catch(IOException ioe) {
        System.out.println("I/O error writing to output file");
            // add this line
        //ioe.printStackTrace();
    }It might say Exception rather than IOException.
    To get a much more useful error message add the commented line.

  • Problem in reading no. of files and writing into a single file

    Hi,
    Iam with Problem in reading no. of files and writing into a single file....
    Iam reading no. of files stored in local directory.......
    Iam able to read and print the data in files successfully....but while writing..only first file is being written...and the next files are not written in my output file...
    plz tell me my mistake....I hope Iam doing some mistake while writing into file...PLz help.....
    Basically my code structure is like this....
    import java.io.*;
    import java.util.regex.*;
    import java.util.*;
    import java.text.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    class Writing {
    public static void main(String args[]) throws Exception {
              FileOutputStream fileOut = new FileOutputStream("ServerResult.xls"); //my output file
              int counter = 1;
              File dir = new File("C:/Perform/ServerLogs");
              String[] children = dir.list();
              if( children == null)
                   System.out.println("The Directory mentioned does not exist");
              else {
                   for (int fileNo = 0; fileNo < children.length; fileNo++ ) {        //Files iteration starts
                        String filename = children[fileNo];
              File logFile = new File(filename);
    FileReader logFileReader = new FileReader(logFile);
    BufferedReader logReader = new BufferedReader(logFileReader);
    StringBuffer sBuf = new StringBuffer(5000);
              HSSFWorkbook wb = new HSSFWorkbook();          
              HSSFSheet sheet = wb.createSheet();
              HSSFRow rowTitle;
              HSSFRow rowReq;
              HSSFRow rowRes;
    String aLine = null;
    boolean skip = false;
    boolean readed = false;
    boolean initReq = false;
              boolean flag = false;
    long requestTime = 0;
    long responseTime = 0;
    long recdTime = 0;
    long sentTime = 0;
              long hasTime = 0;
              long presentTime = 0;
              int hasCalls = 0;
    Pattern startMessage = Pattern.compile("^<MESSAGE.*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern requestMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<ActName>(.*)</ActName>.*", Pattern.DOTALL);
    Pattern requestMessage1 = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<Svc id=\"(.*)\">.*", Pattern.DOTALL);
    Pattern responseMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern initMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"HostConnInit\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern initResMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*", Pattern.DOTALL);
    Pattern initResIDMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*<IATA>"+args[0]+"</IATA>.*", Pattern.DOTALL);
              Pattern sentMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgSentInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
              Pattern rcvdMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgRcvdInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    DecimalFormat dcf = new DecimalFormat("########.##");
    String actName = "";
              if (fileNo ==0)
              rowTitle = sheet.createRow((short)0);
              rowTitle.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)0).setCellValue("Req/Res");
              rowTitle.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)1).setCellValue("Action");
              rowTitle.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)2).setCellValue("Server Time(in ms)");
              rowTitle.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)3).setCellValue("Request Vs Response Time in Server(in ms)");
              rowTitle.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)4).setCellValue("Time Taken By HAS/HOST(in ms)");
              rowTitle.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)5).setCellValue("No. of HAS calls");
              rowTitle.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)6).setCellValue("Data Size");
              //wb.write(fileOut);
    while((aLine=logReader.readLine()) != null) {
    if(aLine.startsWith("<MESSAGE TYPE=\"EVENT\"")) {
    Matcher m = startMessage.matcher(aLine);
    if(m.find()) {
    sBuf.setLength(0);
    sBuf.append(aLine);
    skip = false;
    initReq = false;
    m = initMessage.matcher(aLine);
    if(m.find()) {
    initReq = true;
    } else {
    if(initReq) {
    m = initResMessage.matcher(aLine);
    if(m.find()) {
    sBuf.setLength(0);
    sBuf.append(aLine);
    skip = false;
    } else if(aLine.startsWith("</MESSAGE>")) {
    if(!skip) {
    sBuf.append(aLine);
    readed = true;
    } else if(!skip){
    sBuf.append(aLine);
    if(!skip && readed) {
    String tempStr = sBuf.toString();
    if(tempStr.length() > 0) {
    boolean reqMatched = false;
    Matcher m = null;
    if(initReq) {
    m = initMessage.matcher(tempStr);
    actName = "Intialization";
    } else {
    m = requestMessage.matcher(tempStr);
    String time = "";
    if(m.find()) {
    reqMatched = true;
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    if(i == 1) {
    time = groupStr;
    } else if(i == 2) {
    actName = groupStr;
    } else if(!initReq){
    m = requestMessage1.matcher(tempStr);
    if(m.find()) {
    reqMatched = true;
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    if(i == 1) {
    time = groupStr;
    } else if(i == 2) {
    actName = groupStr;
    if(time.length() > 0 ) {
    try{
    requestTime = sdf.parse(time).getTime();
    }catch(Exception ex){}
    System.out.println("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
                                  //bw.write("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
                                  String reqDataSize = dcf.format(((double)time.length()/1024.0))+"K" ;
                                  rowReq = sheet.createRow((short)counter);
                                       rowReq.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)0).setCellValue("Request");
                                       rowReq.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)1).setCellValue(actName);
                                       rowReq.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)2).setCellValue(time);
                                       rowReq.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)3).setCellValue("");
                                       rowReq.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)4).setCellValue("");
                                       rowReq.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)5).setCellValue("");
                                       rowReq.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)6).setCellValue(reqDataSize);
                                       counter = counter +1;
                                       System.out.println("counter is "+counter);
                             Matcher l = sentMessage.matcher(tempStr);
                             Matcher k = rcvdMessage.matcher(tempStr);
                   if(l.find()) {
                                            for (int i=1; i<=l.groupCount(); i++) {
         String groupStr2 = l.group(i);
    try{
    sentTime = sdf.parse(groupStr2).getTime();
    }catch(Exception ex){}
                        if(k.find())
                                                 for(int j=1;j<=k.groupCount(); j++) {
                                                 String groupStr1 = k.group(j);
                                                 try{
    recdTime = sdf.parse(groupStr1).getTime();
    }catch(Exception ex){}
                                                 presentTime = (recdTime - sentTime);
                                                 hasTime = hasTime + presentTime;
                                                 hasCalls = hasCalls +1;
    if(!reqMatched) {
    if(initReq) {
    m=initResIDMessage.matcher(tempStr);
    } else {
    m=responseMessage.matcher(tempStr);
    if(m.find()) {
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    try{
    responseTime = sdf.parse(groupStr).getTime();
    }catch(Exception ex){}
                                                 String resDataSize = dcf.format(((double)tempStr.length()/1024.0))+"K" ;
                                                 rowRes = sheet.createRow((short)(counter));
                                                 rowRes.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)0).setCellValue("Response");
                                                 rowRes.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)1).setCellValue(actName);
                                                 rowRes.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)2).setCellValue(groupStr);
                                                 rowRes.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)3).setCellValue((responseTime - requestTime));
                                                 rowRes.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)4).setCellValue(hasTime);
                                                 rowRes.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)5).setCellValue(hasCalls);
                                                 rowRes.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)6).setCellValue(resDataSize);
                                                 hasTime = 0;
                                                 hasCalls = 0;
                                                 counter = counter + 1 ;
    sBuf.setLength(0);
    readed = false;
              wb.write(fileOut);
              } // End of for (int fileNo = 0; fileNo < children.length; fileNo++ )
    }     //End of else
              fileOut.close();
    } //End of public static void main
    } // End of Class

    First of all, use [code]-tags to make your code readable, please.
    I didn't do a complete inspection of your code (because it's too much and unreadable as it is) and I don't know POI, but creating a new HSSFWorkbook for each input file sounds fishy to me ... try re-using the workbook and just creating a new sheet in each iteration.

  • Read multiple files and save all into one output file(AGAIN)

    Hi, guys
    I need your help for reading data from multiple files and save the results into one output file. When files are selected from file chooser, my program read the data line by line , do some calculations and save the result into the output. I made an array to store input files and it seems to be working fine, but when it comes to SaveFile() function, issues NullPointException message.
    public class FileReduction1 extends JFrame implements ActionListener
       // GUI definition and layout
        /* ACTION PERFORMED */
        public void actionPerformed(ActionEvent event) {
            if (event.getActionCommand().equals("Open File")) getFileName();
        /* OPEN THE FILE */
        private void getFileName() {
            // Display file dialog so user can select file to open
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(true);
         int result = fileChooser.showOpenDialog(this);
         // If cancel button selected return
         if (result == JFileChooser.CANCEL_OPTION) return;
            if (result == JFileChooser.APPROVE_OPTION)
             files = fileChooser.getSelectedFiles();
                textArea.setText("");
                if(files.length>0)
                    filelist="";
                    System.out.println("files length"+files.length);
                    for(int i=0;i<files.length;i++)
                         System.out.println(files.getName());
    filelist+=files[i].getName()+" ,";
    if (checkFileName(files[i]) )
    openButton.setEnabled(true);
    readButton.setEnabled(true);
    textArea.append("file "+files[i].getName()+"is a proper file"+"\n");
    readFile(files[i]);
    textfield.setText(filelist);
    else{JOptionPane.showMessageDialog(this,"Please select file(s)",
                    "Error 5: ",JOptionPane.ERROR_MESSAGE); }
         // Obtain selected file
    /* READ FILE */
    private void readFile(File fileName_in) {
    // Disable read button
    readButton.setEnabled(false);
    // Dimension data structure
         getNumberOfLines(fileName_in);
         data = new String[numLines][4];
         // Read file
         readTheFile(fileName_in);
         // Rnable open button
         openButton.setEnabled(true);
    /* GET NUMBER OF LINES */
    /* Get number of lines in file and prepare data structure. */
    private void getNumberOfLines(File fileName_in) {
    int counter = 0;
         // Open the file
         openFile(fileName_in);
         // Loop through file incrementing counter
         try {
         String line = fileInput.readLine();
         while (line != null) {
         counter++;
              System.out.println("(" + counter + ") " + line);
    line = fileInput.readLine();
         numLines = counter;
    closeFile(fileName_in);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile(fileName_in);
         System.exit(1);
    /* READ FILE */
    private void readTheFile(File fileName_in)
    // Open the file
    //int row=0;
    int col=0;
    openFile(fileName_in);
    System.out.println("Read the file");
    // Loop through file incrementing counter
    try
    String line = fileInput.readLine();
    while (line != null)
    boolean containsDoubles = false;
    double temp;
    String[] lineParts = line.split("\t");
    try
    for (col=0;col<lineParts.length;col++)
    temp=Double.parseDouble(lineParts[col]);
    data[row][col] = lineParts[col];
    containsDoubles = true;
    System.out.print("data["+row+"]["+col+"]="+lineParts[col]+" ");
    } catch (Exception e) {row=0; col=0; temp=0.0;}
    if (containsDoubles){ row++;}
    System.out.println();
    line = fileInput.readLine();
    catch(IOException ioException)
    JOptionPane.showMessageDialog(this,"Error reading File", "Error 5: ",JOptionPane.ERROR_MESSAGE);
    closeFile(fileName_in);
    System.exit(1);
    //System.out.println("length"+data.length);
    closeFile(fileName_in);
    process(fileName_in);
    /* CHECK FILE NAME */
    /* Return flase if selected file is a directory, access is denied or is
    not a file name. */
    private boolean checkFileName(File fileName_in) {
         if (fileName_in.exists()) {
         if (fileName_in.canRead()) {
              if (fileName_in.isFile()) return(true);
              else JOptionPane.showMessageDialog(null,
                        "ERROR 3: File is a directory");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 2: Access denied");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 1: No such file!");
         // Return
         return(false);
    /* OPEN FILE */
    private void openFile(File fileName_in) {
         try {
         // Open file
         FileReader file = new FileReader(fileName_in);
         fileInput = new BufferedReader(file);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
         textArea.append("OPEN FILE\n---------\n");
         textArea.append(fileName_in.getPath());
         textArea.append("\n");
         //System.out.println("File opened successfully");
    /* CLOSE FILE */
    private void closeFile(File fileName_in) {
    if (fileInput != null) {
         try {
              fileInput.close();
         catch (IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File closed");
    private void process(File fileName_in) {
    //getNumberOfLines();
         //data = new String[numLines][3];
         // Read file
    double temp,temp1;
         //readTheFile();
    //System.out.println("row:"+row);
    //int number=data.length;
    //System.out.println(number);
    for (int i=0; i<row; i++)
    temp=Double.parseDouble(data[i][1]);
    sumx+=temp;
    temp1=Double.parseDouble(data[i][3]);
    sumy+=temp1;
    multixy+=(temp*temp1);
    square_x_sum+=(temp*temp);
    square_y_sum+=(temp1*temp1);
    //System.out.println("Sum(x)="+sumx);
    double tempup=(row*multixy)-(sumx*sumy);
    double tempdown=(row*square_x_sum)-(sumx*sumx);
    slope=tempup/tempdown;
    double tempbup=sumy-(slope*sumx);
    intb=tempbup/row;
    double tempside=(row*square_y_sum)-(sumy*sumy);
    double cordown=Math.sqrt(tempdown*tempside);
    corr=tempup/cordown;
    r_sqrt=corr*corr;
         textArea.append("Data for file"+ fileName_in.getName()+" have been processed successfully.");
         textArea.append("\n");
         textArea.append("Please enter output file name including extension.");
    System.out.println("number"+row);
    System.out.println("slope(m)="+slope);
    System.out.println("intecept b="+intb);
    System.out.println("correlation="+corr);
    System.out.println("correlation="+r_sqrt);
    saveFile();
    private void saveFile()
    textArea.append("SAVE FILE\n---------\n");
    if (openFile1())
         try {
              outputToFile();
    catch (IOException ioException) {
              JOptionPane.showMessageDialog(this,"Error Writing to File",
                   "Error",JOptionPane.ERROR_MESSAGE);
    private boolean openFile1 ()
         // search for the file path
    StringBuffer stringpath;
    title=textfield1.getText().trim();
    int temp=fileName_in.getName().length();
    int temp_path=fileName_in.getPath().length();
    int startd=(temp_path-temp);
    stringpath=new StringBuffer(fileName_in.getPath());
    stringpath.delete(startd, temp_path+1);
    //System.out.println("file-path="+temp_path);
    //System.out.println("length-file="+temp);
    path=stringpath.toString();
    fileName_out = new File(path, title);
    //System.out.println(file_out.getName());
    if (fileName_out==null || fileName_out.getName().equals(""))
         JOptionPane.showMessageDialog(this,"Invalid File name",
                   "Invalid File name",JOptionPane.ERROR_MESSAGE);
         return(false);
         else
    try
    boolean created = fileName_out.createNewFile();
    if(created)
    fileOutput = new PrintWriter(new FileWriter(fileName_out));
    fileOutput.println("File Name"+"\t"+"Slope(m)"+"\t"+"y-intercept(b)"+"\t"+"Coefficient(r)"+"\t"+"Correlation(R-Squared)");
    return(true);
    else
    fileOutput = new PrintWriter(new FileWriter(fileName_out,true));
    return(true);
    catch (IOException exc)
    JOptionPane.showMessageDialog(this,"Please enter the file name","Error",JOptionPane.ERROR_MESSAGE);
    return(false);
    private void outputToFile() throws IOException
    // Initial output
         textArea.append("File name = " + fileName_out + "\n");
         // Test if data exists
         if (data != null)
         fileOutput.println(fileName_in.getName() +"\t"+ slope+"\t"+intb+"\t"+corr+"\t"+r_sqrt);
    textArea.append("File output complete\n\n");
         else
    textArea.append("No data\n\n");
         // End by closing file
    initialcomp();
         fileOutput.close();
    private void initialcomp()
    slope=0.0;
    intb=0.0;
    corr=0.0;
    r_sqrt=0.0;
    sumx=0.0; sumy=0.0; multixy=0.0; square_x_sum=0.0; square_y_sum=0.0;
    for(int i=0;i<data.length;i++)
    for(int j=0;j<data[i].length;j++)
    data[i][j]=null;
    /* MAIN METHOD */
    public static void main(String[] args) throws IOException
         // Create instance of class FileChooser
         FileReduction1 newFile = new FileReduction1("File Reduction Program");
         // Make window vissible
         newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFile.setSize(500,400);
    newFile.setVisible(true);
    Sorry about the long lines.
    As you can see, all input files saved in array called files, however when OpenFile1() function is called, it take input (fileName_in) as a single file not an array. I'm assuming this causes the exception.
    When there's muptiple inputs, program should take each file from getFileName() to outputToFile() sequentially.
    Does anybody have an idea to solve this?
    Thanks a lot!!

    you naming convention is confussing. you should follows Java naming convention..you have a getXXX but decalred the return type as "void"...get usully means to return something...
    your code is doing too much..and hard to follows..
    1. get the selected files
    for each selected file
    process the file and return the result
    write out the result.
    /** close the precious resource */
    public void closeResource(Reader in){
        if (in != null){
            try{ in.close(); }
            catch (Exception e){}
    /** get the total number of line in a file */
    public int getLineCount(File file) throws IOException{
        BufferedReader in = null;
        int lineCount = 0;
        try{
            in = new BufferedReader(new FileReader(file));
            while ((in.readLine() != null)
                lineCount++;
            return lineCount;
        finally{ closeResource (in);  }
    /** read the file */
    public void processFile(File inFile, File outFile) throws IOException{
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try{
            in = new BufferedReader(new FileReader(inFile));
            String line = null;
            while ((in.readLine() != null){
                .. do something with the line
                result.append(....);
            writeToFile(outFile, result.toString());
        finally{ closeResource (in);  }
    public void writeToFile(File outFile, String result) throws IOException{
        PrintWriter out = null;
        try{
            out = new PrintWriter(new FileWriter(outFile, true));  // true for appending to the end of the file
            out.println(result);
        finally{  if (out != null){ try{ out.close(); } catch (Exception e){} }  }
    }

  • File Adapter Overwriting the output files

    Hi All,
    I´m using a File Receiver Adapter to write flat files on to an FTP. Same Communication Channel is used for all types of output files (As per the business requirement the file name(
    MzOutput.txt) shud b same for Deliverz orders, Purchase orders etc...). The receiver legacz szstem reads one file at atime and deletes it. So if i´m writing a Deliverz Order File, i have to wait until the file MzOutput.txt gets deleted and then i have to write the next file using the same name. in order to acheive this, i had used a module processor which waits until that MzOutput.txt gets deleted. Mz problem is
    As there are ´n´ no of orders waiting in the queue, if at 12:14:00 the MzOutput.txt gets deleted, then two threads which check for the existance of the MzOutput.txt file finds nothing and tries to write at same time. as a result, first file got overwritten by the second file.
    I dint check the indicator OverwriteExisting File in the CC configuration.If i use two different CC channels to write the same file, it is giving FTP Exception which is true.
    I´m loosing few deliveries as a result of the above case. Can anzone please help me out in this regard?
    Thnx in Advance
    Anil

    Hi Anil,
    Why dont you write the files with 'Add time stamp' option on for the file name and then the third party/legacy system to read the files in the order which they were created.?
    Another option will be to write these files into a folder with these Add time stamp option/counter option and make a shell script check the folder for the MzOutput.txt file exists in the folder from where the third party/legacy system reads the file and once it has deleted the existing file, then ur files shud be moved in the order in which they were written n the temporary folder.
    This will avoid the queue of messages in the adapter engine.
    Cheers
    JK

  • Adobe Media Encoder Could not write XMP data in output file.

    Hi there i have searched for this on the forums,
    if there is a Thread on it please Link:)
    This is my Encoding Log from Adobe Media ancoder,
    (se Below).
    im doing a projekt from Mts Files, in Premiere pro
    i have Checked the box that no Xmp Data needs to be added, to the left from the Queue button in the export window.
    Should i Delete all the Xmp in Bridge or somthing like that to Resolve this?
    Regards
    Jonas Dwight
    Encoding Log:
    - Source File: /Users/Blasuk/Library/Caches/TemporaryItems/Mogel_oe_2014_nyeste.prproj
    - Output File: /Users/Blasuk/Desktop/Video_Projekts/Fremkaldte/Moegeloe2014-hq.mp4
    - Preset Used: Custom
    - Video: 1920x1080 (1,0), 25 fps, Upper, 01:18:52:10
    - Audio: AAC, 320 kbps, 48 kHz, 5.1
    - Bitrate: VBR, 2 pass, Target 15.00 Mbps, Max 41.30 Mbps
    - Encoding Time: 11:05:14
    01/05/2015 07:35:01 PM : File Encoded with warning
    File importer detected an inconsistency in the file structure of Moegeloe2014-hq.mp4.  Reading and writing this file's metadata (XMP) has been disabled.
    Adobe Media Encoder
    Could not write XMP data in output file.

    Any help please?! Thank you!

  • How to map expdp parallele process to output file

    How to map expdp parallel process to its output file while running...
    say i use expdp dumpfile=test_%U.dmp parallel=5 ..
    Each parallele process writing to its related output file.. i want to know the mapping in run time...

    I'm not sure if this information is reported in the status command but it's worth a shot. You can get to the status command 2 ways:
    if you are running a datapump job from a terminal window, then while it is running, type ctl-c and you will get the datapump prompt. Either IMPORT> or EXPORT>
    IMPORT> status
    If you type status, it will tell you a bunch of information about the job and then each process. It may have dumpfile information in there.
    If you run it interactively, then you need to attach to the job. To do this, you need to know the job name. If you don't know, you can look at sys.dba_datapump_jobs if prived, or sys.user_datapump_jobs if not prived. You will see a job name and a schema name. Once you have that, you can:
    expdp user/password attach=schema.job_name
    This will bring you to the EXPORT>/iMPORT> prompt. Type status there.
    Like I said, I'm not sure if file name information is specified, but it might be. If it is not there, then I don't know of any other way to get it.
    Dean

  • Email conc program output file by using printer driver

    Hi ,
    we have one interface program which has been scheduled every week.
    My req is that after completing successfully/error the interface program i need to send an email to the given email address with output file as attachment.
    This should be happened through priter driver.
    Could anyone please help me on this.
    Thanks,
    Malla

    Hi Bhaskar,
    I appreciate for your reply.
    What I am looking for is that without writing any shell script is there any possible solution.
    Now I am getting an email without writing shell script but attachment is not coming with the email.
    My current process is that
    I am registering a printer and when create a driver for this i am giving parametes for command mode as
    $ uuencode $PROFILES$.FILENAME $PROFILES$.FILENAME_out|mailx -s $ $PROFILES$.FILENAME [email protected]
    I am able to get the email but no attachment.
    So Could you please tell me how to do that.
    Thanks,
    Malla

  • Server/browser requirements for WebHelp output files

    What are the UNIX server and browser requirements in order to
    display a WebHelp project output file correctly?
    When I generate the primary layout, I am not selecting 508
    format, and I select Java Applet as the preferred method for the
    Navigation Pane (checking the radio button for DHTML > Java
    Applet > Pure HTML as the order of preference.
    When viewing the help project on the UNIX server through
    Mozilla, the page appears to load and reload, load and reload.
    Sometims pressing Esc. stops it and you can view the TOC and
    content pane. The way around this is to generate Pure HTML only,
    but then the index and the glossary become very difficult to use.
    Robohelp Webhelp descriptions claim to work on all platforms
    and in all browser types. What requirement are we missing on our
    UNIX server so the project can display correctly?
    Thanks in advance for your time and trouble. :-)

    Hi GEWB,
    Here are some more details--
    Generate Webhelp output setup:
    Use lowercase filenames (recomm. for UNIX)
    Toolbar buttons: Content, Index, Search
    Navigation: Add breadcrumbs links
    Additional options: Enable Highlight Search results, Synchronize TOC automatically
    Navigation Pane preferred format: DHTML > Java Applet > Pure HTML
    Optimize speed for: Web site
    Q: how are you setting up your Linux to open the default project page?
    A: I use Linux only to launch the webehelp output.
    Q: Are you opening the GENERATED project default page or trying to open the project source files?
    A: I am trying to open the generated project default page. I copy the Webhelp folder to a Linux machine and launch the index.html page to see the output.
    Q: Why are you replacing the foreward-backward slash?
    A: In Linux '\' is not supported for hyperlinks/filepaths. Therefore I changed the backward slashes to forward slashes.
    The scenario:
    When the project files have filepath such as ../../doc/xyz/,
    when I view in Windows (IE)- I can access the link
    when I view in Linux (FF)- I see broken link with error message somewhat like "cannot find ..\..\doc\xyz\". (Note the changed usage of slash)
    This indicates that the generated files changes the forward slash to backward.

Maybe you are looking for