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()); }
}
Similar Messages
-
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. -
How to avoid output file and error lines when condition does not match
Hi Experts
A customer want to send purchase order files to several vendors and each vendor has their own requirement to content and file format. I have prepared scenarios for each vendor and a template is (conditionally) called when CardCode matches. It works fine, - PO file is generated when CardCode matches, but error lines are written to SAP B1 Control Center each time CardCode does not match the one defined in a scenario (100 or more times per day). Problem is that these error lines does not get automatic deleted. Conditional processing are made in this way:
Result Message in SAP B1 Control Center when CardCode does not match:
I tried to avoid an error line in SAP B1 Control Center when CardCode does not match in this way:
Then no error lines are written to SAP B1 Control Center, but an output file is generated each time (order file when CardCode matches and an empty file when CardCode does not match).
Any suggestions on how to avoid both errors types (error lines in SAP B1 Control Center and empty output files)?
Or - can lines in SAP B1 Control Center be automatic deleted?
Regards
SteenHi Steen,
using <b1im_skip> should be the right approach, if you're working with B1 OUTBOUND.
Following extract form the B1i help describes the usage to skip the outbound processing:
1.1 Skipping Outbound Processing
If you do not want to hand over the message to the receiver system, the scenario step can create a special tag that indicates to generic processing in the integration framework to skip the message processing.
Add the following to the final transformation atom (atom0):
<b1im_skip xmlns= ”” info=”my info” msglog=”true” msgout="yes">
If the integration framework skips the message, it puts the message log information to the Filtered section, if the message log is switched on. The result message contains the Message skipped by vBIU logic information.
info
To display an individual message, define it using the info attribute.
msglog
If you want to avoid an entry in the message log, introduce the msglog attribute and set it to false.
msgout
To display the skip information in the Success section of the message log, use the msgout attribute and set it to yes.
In case you don't want any MsgLogEntry in case of a skipped message, please enter the following in final atom0:
<xsl:template name="transform">
<xsl:attribute name="pltype">xml</xsl:attribute>
<xsl:choose>
<xsl:when test="$msg/BOM/BO/Documents/row/CardCode='C20000'">
<xsl:call-template name="transform2"/>
</xsl:when>
<xsl:otherwise>
<b1im_skip info="skipped" msglog="false"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Best regards
Bastian -
when I open up an e-mail attachment a box pops up PRINT TO FILE below that line OUTPUT FILE NAME with an empty line for the file name vs. simply going to my default printer?
Make sure that '''''Print to File''''' isn't selected in the native print dialog box ''(see screenshot below)'' middle-right, and make sure your Printer is selected at the top of that dialog box.
''I'm a little confused why an email attachment would need to go directly to the printer, but that's what you asked about.'' -
PDF file lines aren't vectors but rectangles.
I have a PDF file which has been produced in Indesign (it may originally have been created in Illustrator or Photoshop).
On opening the PDF most of the vector parts of the file are not true lines but seem to be rectangles or the outer edges of a line in this particular case 0.105mm's apart.
I have noticed this before with PDF's and it is very frustrating.
I am trying to create a dieline from these files and if I tried to create a cutting die from this, the laser would create an unholy mess when it tried to burn.
Is there some kind of setting that makes sure the PDF is created with true vector lines?
If anyone could shed some light on this I would be most grateful.
Many Thanks in advance,
DahzeeBob & Grant, thanks for taking the time to reply.
Could you please just give me one more piece of information.
I am so far down the food chain from whoever is doing the Artwork, I get very little say in how this is created.
Is there one instruction I can pass back up the line to the Designers that could give me at least a fighting chance of having a decent single line file to make my dielines?
I am a CAD guy so I have no concept of what the Designers are doing in Illustrtator, Indesign or Photoshop.
Thanks again in advance.
Dahzee -
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: AjayI 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 -
Help With Writing A Vector To A File
hi
i am having trouble writing a vector to a file
Here is my code
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.filechooser.*;
public class Save
JFileChooser fc = new JFileChooser();
public Save(JFrame par, mainCollection col)
try
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream fc.getSelectedFile().getName()));
out.writeObject(col.carCollection);
for(int i = 0; i< col.carCollection.size();i++)
Cars cd = (Cars)col.carCollection.elementAt(i);
Vector v = cd.getModels();
out.writeObject(v);
}catch(FileNotFoundException e){System.out.println("not found");}
catch(IOException e){System.out.println("IO" + e.getMessage());}
Ok now the mainCollection col is from my other class mainCollection which has my main vector in it. This main vector contains car types which contain car models i.e. Ford which contains Falcon. What i need to do is copy the whole contents of vector over in one go to the file.
With the code above i am getting IO Exception errors
here is the errors
�� sr java.util.Vector��}[�;� I capacityIncrementI elementCount[ elementDatat [Ljava/lang/Object;xp ur [Ljava.lang.Object;��X�s)l xp
{sr java.io.NotSerializableException(Vx ��5 xr java.io.ObjectStreamExceptiond��k�9�� xr java.io.IOExceptionl�sde%�� xr java.lang.Exception��>;� xr java.lang.Throwable��5'9w�� L
detailMessaget Ljava/lang/String;xpt Cars
Whatever all that means
Thanks for your help, i'm really confused
DaJavaLodown
Remove the for loop.
If you write the vector, it's content will be written too.
hi
i am having trouble writing a vector to a file
Here is my code
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.filechooser.*;
public class Save
JFileChooser fc = new JFileChooser();
public Save(JFrame par, mainCollection col)
try
ObjectOutputStream out = new
= new ObjectOutputStream(new FileOutputStream
fc.getSelectedFile().getName()));
out.writeObject(col.carCollection);
for(int i = 0; i<
= 0; i< col.carCollection.size();i++)
Cars cd =
Cars cd = (Cars)col.carCollection.elementAt(i);
Vector v = cd.getModels();
out.writeObject(v);
}catch(FileNotFoundException
ion e){System.out.println("not found");}
catch(IOException e){System.out.println("IO" +
" + e.getMessage());}
Ok now the mainCollection col is from my other class
mainCollection which has my main vector in it. This
main vector contains car types which contain car
models i.e. Ford which contains Falcon. What i need to
do is copy the whole contents of vector over in one go
to the file.
With the code above i am getting IO Exception errors
here is the errors
�� sr java.util.Vector��}[�;� I
capacityIncrementI elementCount[ elementDatat
[Ljava/lang/Object;xp ur
r [Ljava.lang.Object;��X�s)l xp
{sr java.io.NotSerializableException(Vx ��5 xr
java.io.ObjectStreamExceptiond��k�9�� xr
java.io.IOExceptionl�sde%�� xr
r java.lang.Exception��>;� xr
java.lang.Throwable��5'9w�� L
detailMessaget Ljava/lang/String;xpt Cars
Whatever all that means
Thanks for your help, i'm really confused
DaJavaLodown -
hi friends
using `n how can i add two empty line (two carriage return), between these two lines in the output file?
PS C:\> $env:COMPUTERNAME | add-content c:\file.txt
PS C:\> $Env:USERDOMAIN | add-content c:\file.txt
i tested "$env:computername`n`n`n$env:userdomain" | add-content c:\file.txt but it results in
myPCMyDomain
but i wanted the contents of the output file be like this:
MyPC
#empty line here
#empty line here
MyDomain
i tested many other forms but didn't work.
thanksI tried it, as well. The line breaks were respected in the PowerShell console, Programmer's Notepad, and Word; they weren't in Notepad.
You are using a Unicode file. Locale is what?
If you just want notepad compatible line breaks then do this:
del file.txt ; "$env:computername`r`n`r`n`r`n$env:userdomain" | add-content file.txt ;notepad file.txt
Look in hex to see that `n is ^L or 0xA and is only one character. CrLf is 0xD 0xA - two characters.
My programmers editors and VS all understand a single ^L as a line break so does PowerShell. Only DOS/Notepad and other utilitis don't understand this..
¯\_(ツ)_/¯ -
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? -
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
ArunaTry
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 -
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){} } }
} -
Hi
Could somebody tell me how to read file line by line ? Namely my input file I want to read look as follow:
AAA 1, 1
12 222 12
AAA 2, 2
11 122 11
My output file should look as follow:
1, 1, 12
1, 1 222
1, 1, 12
2, 2, 11
2, 2, 122
2, 2, 11
I think the lines need to be stored in ArrayList, then I would like those lines to write to csv file, but how on read I can construct such output file? This is my code for reading file
public ArrayList readFile(String filename)
try
BufferedReader in = new BufferedReader(new FileReader(filename));
ArrayList list = new ArrayList();
String lineS = null;
while (in.ready())
if ((lineS = in.readLine()).startsWith("")){
String[] line = in.readLine().trim().split("\\s+");
list.add(Integer.valueOf(line[0]));
list.add(Integer.valueOf(line[1]));
list.add(Integer.valueOf(line[2]));
in.close();
return list;
catch (Exception e)
e.printStackTrace();
return null;
ThanksThe rules for the conversion from input to the desired output are:
1. For each of the line with string take 2 integers for example 1, 1 from AAA 1, 1
2. Then repeat 1, 1 for each next number not containing any string, so if the line after AAA, 1, 1 has 12, 222, 12 then the output will look as follow
1, 1, 12
1, 1 222
1, 1, 12
3. Repeat the process (the pattern is the same 1 line with string 1 line with numbers)
Actually I am not sure how to perform that logic for such conversion as for now I am only able to list only the numbers but I have a problem to add numbers from the line having string in it.
STOP!
You should NOT be writing code if you are 'not sure how to perform that logic'.
You are getting ahead of yourself.
There is NOTHING to gain by trying to code a solution before you know what algorothm you need. Big mistake.
Should I use list or maybe if the patter for lines is the same array will be more sufficient?
NEITHER ONE!
Those are 'solutions' used to implelment an algorothm.
You do NOT yet know what algorithm you need to use so how can you possibly write code to implement the unknown?
How to perform logic to get the numbers from line having string and for the next lines having only numbers in order to structure it into desired output?
THAT is the question your thread subject should have.
Until you get the answer to it don't write any code,.
Do NOT try to automate what you can't do manually.
Write down, on paper or use an editor, the step by step 'logic' you need and walk through that logic from beginning to end until the 'logic' works and produces the correct result.
You just now have started to do that when you listed those rules above.
But you left some things out. Expand on that list of 'rules' and provide a little more example data. TPD has given you a good example. Reread what they said.
Did you notice they start by talking about 'tasks': what each task does and the order the tasks need to be performed.
That 'task list' has NOTHING to do with Java, C, or any other language: it is identifying the problem/algorithm. Until you have that coding is premature. -
Help!! writeUTF is writing some junk chars to my file
hi guys,
I am breaking my head with this. please help me out
I wrote a servlet which reads the input sent by an applet
the applet sends a hashmap object called manifest to the servlet
i am reading the contents of this manifest object into a file using writeUTF
but when i open the file to check the contents
every line has some erroneous characters at the beggining of the line
i am not understanding why these junk characters are writted, when i am making sure that i am writing correctly
i am appending the code also to this, please verify:
File lmin = new File(userFile.getPath()+"/"+"Lmin.txt");
FileOutputStream tolmin = new FileOutputStream(lmin);
DataOutputStream dos = new DataOutputStream(tolmin);
out.writeUTF("s&f"+(String)manifest.get("s&f")); //manifest is Hashmap object
dos.writeUTF(manifest.get("-s").toString().trim()+"\n");
when i am printing manifest.get("-s").toString().trim() to the outputstream it doesn't show any additional characters, but the file Lmin.txt has these junk characters.
why is this so??
thanks
pre_praI've simplified your code.
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
DataOutputStream dos = new DataOutputStream (new FileOutputStream (new File ("test.bin")));
dos.writeUTF ("123456");
dos.close();
}The output is written to a file named test.bin. I've printed the hex dump of the file.
C>hd test.bin
0000 00 06 61 62 63 64 65 66 ..abcdefYou can see from the dump that writeUTF writes the length of the string (00 06) and then the bytes, encoded in UTF-8 (just ASCII in my case). The junk that you can see in your file is the length of the string that writeUTF wrote to the output file. -
Adding lastline in the output file
hi
i have attached my coding with this just i need to add a word in before of last line in output file
please help out....
import java.io.*;
import java.io.FileReader;
class Filenew
public static void main(String args[]) throws IOException
FileReader in = new FileReader("e:/rag.txt");
FileWriter out= new FileWriter("e:/out2.txt");
BufferedReader br=new BufferedReader(in);
String s;
while((s=br.readLine())!=null)
out.write(s);
out.close();
in.close();
}regards
Raghavanhi,
From your previous post
http://forum.java.sun.com/thread.jspa?threadID=5226088you are trying to write in a file and add some text before last line in that file,
if yes
here is the modified code,
try to even better;
file.java
import java.io.*;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import java.util.Enumeration;
public class file
public static void main(String args[]) throws IOException
InputStream in = new FileInputStream("out2.txt");
FileWriter fo=new FileWriter("out3.txt");
Vector v = new Vector ();
int c,pos,pos1;
String s=new String();
StringBuffer sb = new StringBuffer();
while((c=in.read())!=-1)
sb.insert(0,(char)c);
sb = sb.reverse();
s = sb.toString();
pos = s.indexOf("verify scan_test",0);
s=s.substring(pos+1);
int linecount = 0;
while (pos >= 0) {
s = s.substring(pos + 1);
pos = s.indexOf("_cpdp_=", pos);
pos = s.indexOf("=", pos);
pos1 = s.indexOf(';', pos);
v.add(s.substring(pos + 1, pos1));
++linecount;
Enumeration e = v.elements ();
String str = "";
while ( e.hasMoreElements())
{ --linecount;
if( linecount == 0)
str = "what code you to add here \n\r" + e.nextElement ();
else
str = e.nextElement().toString();
fo.write( str +"\n\r" );
fo.close();
out2.txt
verify scan_test {
Abb {* verify:0 Value:0 lifecycle:0 *}
W tset_tp;
S { _cpdp_=YYYY10YYYYYYYYYYYYYYYYYYY;
Abb {* Begin loop test *}
S { _cpdp_=YYYY10YYYYYYYYYYYYYYYYYYY;
S { _cpdp_=YYYY110YY1YYYYYYYYYYYYYYY;
S { _cpdp_=YYYY110YY1YYYYYYYYYYYYYYY;
S { _cpdp_=YYYY111YY1YYYYYYYYYYYYYYY;
}i hope it will give you a clear cut idea -
XML PUBLISHER/XDO ERROR - Output file was found but is zero sized - Delete
Hi XML/XDO experts,
I am running a XLM publisher report in an internal 12.1 env (mz1dv213) and have this warning when running.
Beginning post-processing of request 40256141 on node RWS60183REMS at
23-JUL-2010 09:34:48.
Post-processing of request 40256141 failed at 23-JUL-2010 09:34:54 with the
error message:
One or more post-processing actions failed. Consult the OPP service log for
details.
+--------------------------
OPP log shows
[072310_010929110][][EXCEPTION] [DEBUG] [sun.cpu.isalist]:[]
[7/23/10 1:09:31 PM] [1925014:RT40257178] Output file was found but is zero sized - Deleted
[7/23/10 1:09:31 PM] [UNEXPECTED] [1925014:RT40257178]
java.lang.reflect.InvocationTargetException
I also have the same issue at a Customer site (bug is escalated)
Please adviseI'm having the same problem.
I'm getting this error in R12.1.3. Does anyone have solution for this?
I tried the solution given in the link - "http://forums.oracle.com/forums/thread.jspa?messageID=9552336�", but it didn't work for me.
Thanks in advance.
Thanks,
Satish
----------LOG FILE-------------
GF AP Custom Application: Version : 12.0.0
Copyright (c) 1979, 1999, Oracle Corporation. All rights reserved.
XXGFAPBAAT_XML module: GF AP Bank Account Audit Trail Report
Current system time is 28-APR-2011 22:47:23
XDO Data Engine Version No: 5.6.3
Resp: 50863
Org ID : 81
Request ID: 1427740
All Parameters: P_CREATION_DATE_FR=:P_CREATION_DATE_TO=:P_CREATED_BY=
Data Template Code: XXGFAPBAAT_XML
Data Template Application Short Name: XXAP
Debug Flag: N
{P_CREATED_BY=, P_CREATION_DATE_TO=, P_CREATION_DATE_FR=}
Calling XDO Data Engine...
[042811_104733608][][STATEMENT] Start process Data
[042811_104733751][][STATEMENT] Process Data ...
[042811_104733752][][STATEMENT] Executing data triggers...
[042811_104733752][][STATEMENT] BEGIN
XXGF_AP_BAAT_XML_PKG.P_CONC_REQUEST_ID := :P_CONC_REQUEST_ID ;
XXGF_AP_BAAT_XML_PKG.P_CREATION_DATE_FR := :P_CREATION_DATE_FR ;
XXGF_AP_BAAT_XML_PKG.P_CREATION_DATE_TO := :P_CREATION_DATE_TO ;
XXGF_AP_BAAT_XML_PKG.P_CREATED_BY := :P_CREATED_BY ;
:XDO_OUT_PARAMETER := 1;
END;
[042811_104733752][][STATEMENT] 1:0 :
[042811_104733752][][STATEMENT] 2: :
[042811_104733753][][STATEMENT] 3: :
[042811_104733753][][STATEMENT] 4: :
[042811_104733763][][STATEMENT] Executing data triggers...
[042811_104733763][][STATEMENT] Declare
l_flag Boolean;
BEGIN
l_flag := XXGF_AP_BAAT_XML_PKG.BeforeReport() ;
if (l_flag) then
:XDO_OUT_PARAMETER := 1;
end if;
end;
[042811_104733771][][STATEMENT] P_CONC_REQUEST_ID
[042811_104733771][][STATEMENT] P_CREATION_DATE_FR
[042811_104733771][][STATEMENT] P_CREATION_DATE_TO
[042811_104733771][][STATEMENT] P_CREATED_BY
[042811_104733771][][STATEMENT] Writing Data ...
[042811_104733780][][STATEMENT] &srwhereclause
[042811_104733795][][STATEMENT] &srwhereclause1
[042811_104733797][][STATEMENT] Sql Query :Q_AUDIT_TRIAL: SELECT DECODE(abaaa.audit_transaction_type,
'I','INSERTION',
'U','UPDATE',
'D','DELETION',
NULL) activity,
SUBSTR(abb.bank_name,1,24) bank_name,
-- SUBSTR(abb.bank_number,1,25) bank_number, -- Commented by Bugoy 18-SEP-2003
SUBSTR(abb.bank_branch_name,1,20) branch_name,
SUBSTR(abb.bank_num,1,15) branch_number,
SUBSTR(abaaa.bank_account_name,1,30) old_bank_account_name,
SUBSTR(abaaa.bank_account_num,1,25) old_bank_account_number,
-- SUBSTR(abaa.bank_account_name,1,30) new_bank_account_name, -- Commented by Bugoy 18-SEP-2003
SUBSTR(abaa.bank_account_name,1,50) new_bank_account_name, -- Added by Bugoy 18-SEP-2003
SUBSTR(abaa.bank_account_num,1,25) new_bank_account_number,
SUBSTR(abaaa.audit_user_name,1,15) created_by,
TO_CHAR(abaaa.audit_timestamp,
'DD-MON-YYYY HH:MI:SS AM') creation_date
FROM ap_bank_branches abb,
xxgf_ap_bank_accounts_all_a abaaa,
ap_bank_accounts_all abaa
WHERE abaaa.bank_account_id = abaa.bank_account_id
AND abaa.bank_branch_id = abb.bank_branch_id
-- AND TRUNC(abaaa.audit_timestamp) BETWEEN to_date(:P_CREATION_DATE_FR,) AND :P_CREATION_DATE_TO
-- AND abaaa.audit_user_name = NVL(:P_CREATED_BY,abaaa.audit_user_name) -- Added By Bugoy 04-SEP-2003
AND abaa.set_of_books_id = FND_PROFILE.VALUE('GL_SET_OF_BKS_ID') -- Added By Bugoy 16-DEC-2003
AND abaa.org_id = FND_PROFILE.VALUE('ORG_ID') -- Added By Adi 12-JUL-2010 PSR-10-4725
and 1=1
and 1=1
ORDER BY SUBSTR(abaa.bank_account_name,1,50);
--SQLException
java.sql.SQLSyntaxErrorException: ORA-00911: invalid character
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:439)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:395)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:802)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:205)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:861)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1145)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1267)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3449)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3493)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
at oracle.apps.xdo.dataengine.XMLPGEN.processQuery(XMLPGEN.java:1947)
at oracle.apps.xdo.dataengine.XMLPGEN.processSQLDataSource(XMLPGEN.java:501)
at oracle.apps.xdo.dataengine.XMLPGEN.writeData(XMLPGEN.java:445)
at oracle.apps.xdo.dataengine.XMLPGEN.writeGroupStructure(XMLPGEN.java:308)
at oracle.apps.xdo.dataengine.XMLPGEN.processData(XMLPGEN.java:273)
at oracle.apps.xdo.dataengine.XMLPGEN.processXML(XMLPGEN.java:215)
at oracle.apps.xdo.dataengine.XMLPGEN.writeXML(XMLPGEN.java:254)
at oracle.apps.xdo.dataengine.DataProcessor.processDataStructre(DataProcessor.java:390)
at oracle.apps.xdo.dataengine.DataProcessor.processData(DataProcessor.java:355)
at oracle.apps.xdo.oa.util.DataTemplate.processData(DataTemplate.java:334)
at oracle.apps.xdo.oa.cp.JCP4XDODataEngine.runProgram(JCP4XDODataEngine.java:294)
at oracle.apps.fnd.cp.request.Run.main(Run.java:157)
Start of log messages from FND_FILE
P_CREATION_DATE_FR:
P_CREATION_DATE_TO:
P_CREATED_BY:
srwwhereclause 1=1
srwwhereclause1 1=1
End of log messages from FND_FILE
Executing request completion options...
Output file size:
230
------------- 1) PUBLISH -------------
Beginning post-processing of request 1427740 on node SGPERPVMEBSDB1 at 28-APR-2011 22:47:34.
Post-processing of request 1427740 failed at 28-APR-2011 22:47:35 with the error message:
One or more post-processing actions failed. Consult the OPP service log for details.
Finished executing request completion options.
Concurrent request completed
Current system time is 28-APR-2011 22:47:36
---------------------CONCURRENT MANAGER LOG--------------------------
[4/28/11 10:47:35 PM] [OPPServiceThread1] Post-processing request 1427740.
[4/28/11 10:47:35 PM] [96895:RT1427740] Executing post-processing actions for request 1427740.
[4/28/11 10:47:35 PM] [96895:RT1427740] Starting XML Publisher post-processing action.
[4/28/11 10:47:35 PM] [96895:RT1427740]
Template code: XXGFAPBAAT_XML
Template app: XXAP
Language: en
Territory: 00
Output type: null
[4/28/11 10:47:35 PM] [96895:RT1427740] Output file was found but is zero sized - Deleted
[4/28/11 10:47:35 PM] [UNEXPECTED] [96895:RT1427740] java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor271.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at oracle.apps.xdo.common.xml.XSLT10gR1.invokeParse(XSLT10gR1.java:570)
at oracle.apps.xdo.common.xml.XSLT10gR1.transform(XSLT10gR1.java:235)
at oracle.apps.xdo.common.xml.XSLTWrapper.transform(XSLTWrapper.java:182)
at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:1044)
at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:997)
at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:212)
at oracle.apps.xdo.template.FOProcessor.createFO(FOProcessor.java:1665)
at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:975)
at oracle.apps.xdo.oa.schema.server.TemplateHelper.runProcessTemplate(TemplateHelper.java:5936)
at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3459)
at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3548)
at oracle.apps.fnd.cp.opp.XMLPublisherProcessor.process(XMLPublisherProcessor.java:302)
at oracle.apps.fnd.cp.opp.OPPRequestThread.run(OPPRequestThread.java:176)
Caused by: org.xml.sax.SAXParseException: <Line 6, Column 1>: XML-20210: (Fatal Error) Unexpected EOF.
at oracle.xdo.parser.v2.XMLError.flushErrorHandler(XMLError.java:441)
at oracle.xdo.parser.v2.XMLError.flushErrors1(XMLError.java:303)
at oracle.xdo.parser.v2.XMLReader.popXMLReader(XMLReader.java:530)
at oracle.xdo.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1312)
at oracle.xdo.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:338)
at oracle.xdo.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:285)
at oracle.xdo.parser.v2.XMLParser.parse(XMLParser.java:289)
... 16 more
[4/28/11 10:47:35 PM] [96895:RT1427740] Completed post-processing actions for request 1427740.
Edited by: user6665827 on Apr 28, 2011 10:56 PM
Maybe you are looking for
-
SP2-0027: Input is too long -error on pl/sql procedure
Hi, We are on Oracle 11.2.0.2 on Solaris 10. I have a procedure call that errors out with this error: SP2-0027: Input is too long (> 2499 characters) - line ignored It is one single procedure but it takes too many long inputs in it. This giant proced
-
Save As takes over 30 seconds to show Save As dialog.
Every time I click File - Save As it takes over 30 seconds for the Save As dialog window to show up. I am using Adobe Acrobat 9 Pro Version 9.5.2
-
Can anyone explain why when I signed up to BT broadband some 4 years ago the estimated line speed I would get was estimated at 3.5Mbps (I was actually getting between 1 and 2 and every so often 2.5). Recently I've noticed a drop in speed, last week t
-
I Cant inst i Tunes for i poc touch
-
Dreamweaver CS6 crashes when editing tables
When I'm editing a table in the design view of Dreamweaver CS6, it stops responding and crashes. I have tried restarting my computer, restarting Dreamweaver (obviously) and repeating the same process, but it crashes in the exact same place. CS5.5 nev