4 bytes into one int
Hi, I have four bytes in my program, I'd add them together somehow so that i have a 32bit string, how can I do this?
I tried adding them together and storing into an int but when i tried to do bit shifting I got an unexpected result.
int x = byte[0] + byte[1] + byte[2] + byte[3];Where am i going wrong?
thx
Edited by: Unconditional on Jan 25, 2008 12:35 PM
You need to use bit shifting. However, you need to decide whether [0] is the high byte or the low byte (big-endian or little-endian).
EDIT: Also, "32bit string"? You mean "32-bit int" right?
Edited by: paul.miner on Jan 25, 2008 2:39 PM
Similar Messages
-
Converting a byte[] into an int
I am using the MD5 hash function to create a message digest. When the hash function is complete it returns a byte[]. I want to turn this byte [] into an int, so that I can exclusive or (^) it to a node id according to this traceback algorithm I am trying to implement.
Basically, I need to turn a byte[] into an int, and then from an int back into a byte[].
I've looked throughout the forums at different implementations of this, but some do not return the same byte[] as the original, other's have said to use the ByteBuffer, but how do I use it to turn a byte[] into an int?
Any help would be great, thanks!!!Unfortunatly that will not work. As a previousposter
indicated, you must mask off the lower 8 bits ofeach
byte after converting to int (or the equivilentmask
after shifting).Um? Why would the "sign" bit be getting shifted INTO
the lowest bit?D'oh! Sorry. My bad. When bytes[n] gets "implicitly" cast to do the calculation. Gak! Nevermind.
Corrected would be:
iBytesVal = ((bytes[3] & 0xFF) << 24);
iBytesVal |= ((bytes[2] & 0xFF) << 16);
iBytesVal |= ((bytes[1] & 0xFF) << 8);
iBytesVal |= (bytes[0] & 0xFF); -
How to join fields from different internal tables and display into one int
hai i have one doubt...
how to join fields from different internal tables and display into one internal table..
if anybody know the ans for this qus tell me......hii
you can read data as per condition and then can join in one internal table using READ and APPEND statement..refer to following code.
SELECT bwkey " Valuation Area
bukrs " Company Code
FROM t001k
INTO TABLE i_t001k
WHERE bukrs IN s_bukrs.
IF sy-subrc EQ 0.
SELECT bwkey " Valuation Area
werks " Plant
FROM t001w
INTO TABLE i_t001w
FOR ALL ENTRIES IN i_t001k
WHERE bwkey = i_t001k-bwkey
AND werks IN s_werks.
IF sy-subrc EQ 0.
LOOP AT i_output INTO wa_output.
READ TABLE i_t001w INTO wa_t001w WITH KEY werks = wa_output-werks.
READ TABLE i_t001k INTO wa_t001k WITH KEY bwkey = wa_t001w-bwkey.
wa_output-bukrs = wa_t001k-bukrs.
MODIFY i_output FROM wa_output.
CLEAR wa_output.
ENDLOOP. " LOOP AT i_output
ENDIF. " IF sy-subrc EQ 0
regards
twinkal -
How to cram two bytes into a short?
Hi all,
I have some byte[] data that I am receiving, and I need to put two bytes into one short (or int, or whatever), as the byte[] will form a two bytes-per-pixel image. I've been working with 8-bit data (this is 12-bits, NOT packed), which is much easier to manipulate.
I currently have this method to convert a byte[] of 8-bit data into a short (I do this because Java does not support signed types and I need that 8th bit):
private short[] convertBytesToShorts(byte[] data) {
short[] convertedData = new short[data.length];
for (int i = 0; i < data.length; i++) {
convertedData[i] = (short)((short)data[i] & 0xff);
return convertedData;
}Is there a way to modify this to place two bytes into one short? Is it possible to just AND two bytes with 0xff and add them together to create one short? Surely it cannot be that simple. Also, remember that I must treat the values as unsigned.
Furthermore, the two bytes look like this:
| xxxx xxxx | xxxx 0000 |So the last four bits in the second byte are 0s.
Any advice is appreciated.
Message was edited by:
DjaunlI've been working with 8-bit
data (this is 12-bits, NOT packed), Obviously that is contradictory.
I currently have this method to convert a byte[] of
8-bit data into a short (I do this because Java does
not support signed types and I need that 8th bit):
Yes it does. The fact that it displays a byte as and integer and the conversion in that process produces a negative display value has nothing at all to do with the bits.
Is there a way to modify this to place two bytes into
one short? short s = (short)(((b1 << 8) & 0x0ff) | (b2 & 0x0ff))
Of course you still have to deal with getting the order correct.
(You can probably get rid of that first mask but you would need to test that.) -
Java writing out bytes from one file, reading back in again
Hi, I'm having some trouble with bytes.
I have one program which outputs the following bytes into a file (using Printstream.write() - I'm sure that this program is working fine):
4 0 64 0 4 0 128 0 63 223 64 20 4 16 130 0 60 16 64 1 63 223 79 236 64 16 195 232 116 63 255 232 148 0 0 0
I'm then reading in the bytes using the code given on this page (http://www.exampledepot.com/egs/java.io/File2ByteArray.html)
and I get...
4 0 64 0 4 0 -128 0 63 -33 64 20 4 16 -126 0 60 16 64 1 63 -33 79 -20 64 16 -61 -24 116 63 -1 -24 -108 0 0 0
As you can see I now have negative numbers - I noticed that if I do 256 + (the negative number) then i get the number I originally wrote out
I tried fixing this when I read in by doing
bytes[i] = (byte) (256 + bytes);
but it doesn't change anything
how can I either change it so it reads in the bytes exactly as i wrote them out, or write a bit of code that takes the negatives and converts them to the original positives?
thxUnconditional wrote:
Integer x1 = (bytes[i] << 24) & 0xFF;
Integer x2 = (bytes[i+1] << 16) & 0xFF;
Integer x3 = (bytes[i+2] << 8) & 0xFF;
Integer x4 = (bytes[i+3] << 0) & 0xFF;is what I'm doing
System.out.println("x1 " + x1 + " x2 " + x2 + " x3 " + x3 + " x4 " + x4);
returns
x1 0 x2 0 x3 0 x4 0
x1 0 x2 0 x3 0 x4 4
x1 0 x2 0 x3 0 x4 0
x1 0 x2 0 x3 0 x4 128
x1 0 x2 0 x3 0 x4 0
x1 0 x2 0 x3 0 x4 63
x1 0 x2 0 x3 0 x4 223
x1 0 x2 0 x3 0 x4 64
x1 0 x2 0 x3 0 x4 20What are you trying to do? Combine the bytes into an int? -
Hi,
I'm using version 2.1 and getting the following exception
System.InvalidOperationException: The event is too big to fit into one page. The maximum event size is '230' bytes, but the event size is '234' bytes. Try reduce the size of the event payload.
Everywhere I read tells me the maximum page size is 16K, so why am I hitting a 230 byte limit? Secondly how can I increase this to the full 16K?
Thanks,
JeremyThat is ... unusual. I've never seen that. Can you provide some details on what your payload looks like and the query?
DevBiker (aka J Sawyer)
Microsoft MVP - Sql Server (StreamInsight)
If I answered your question, please mark as answer.
If my post was helpful, please mark as helpful. -
How can I convert an array off byte into an Object ?
Hi folks...
I�m developing an application that comunicates a PDA and a computer via Wi-Fi. I�m using a DataStream ( Input and Output ) to receive / send information from / to the computer. Most off the data received from him is in the byte[] type...
How can I convert an array off byte ( byte[] ) into an Object using MIDP 2.0 / CLDC 1.1 ?
I found on the web 2 functions that made this... but it uses a ObjectOutputStream and ObjectInputStream classes that is not provided by the J2ME plataform...
How can I do this ?
Waiting answers
Rodrigo KerkhoffThere are no ObjectOutputStream and ObjectInputStream classes in CLDC. You must know what you are writing to and reading from the DataStream. You should write the primitives like int, String to the DataOutputstream at one end and read those in exactly the same sequence at the outher end using readInt(), readUTF() methods.
-
Mapping complete input XML structure into one field on target
Hi,
I have a scenario where I need to map the complete input XML structure as it is, into one field on target side. so can we achieve this in Graphical Mapping? If yes, please share your valuable info.
Regards,
Shiva.Hello,
this is the java map code.just compile it and made a .zip file import it and use it Interface Mapping.
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.AbstractTrace;
import com.sap.aii.mapping.api.StreamTransformationConstants;
import java.util.Map;
import java.io.*;
public class PayloadToXMLField1 implements StreamTransformation {
String strXML = new String();
//Declare the XML tag for your XML message
String StartXMLTag = "<DocumentBody>";
String EndXMLTag = "</DocumentBody>";
//String StartXMLTag1 = "<Code>";
//String EndXMLTag1 = "</Code>";
AbstractTrace trace;
private Map param = null;
public void setParameter(Map param) {
this.param = param;
public void execute(InputStream in, OutputStream out) {
trace =
(AbstractTrace) param.get(
StreamTransformationConstants.MAPPING_TRACE);
trace.addInfo("Process Started");
try {
StringBuffer strbuffer = new StringBuffer();
byte[] b = new byte[4096];
for (int n;(n = in.read(b)) != -1;) {
strbuffer.append(new String(b, 0, n));
strXML = strbuffer.toString();
} catch (Exception e) {
System.out.println("Exception Occurred");
String outputPayload =
StartXMLTag
+ "<![CDATA["
+ strXML
+ "]]>"
+ EndXMLTag;
try {
out.write(outputPayload.getBytes());
trace.addInfo("Process Completed");;
} catch (Exception e) {
trace.addInfo("Process Terminated: Error in writing out payload");; -
Why is there only read(byte[]) & not read(int[])
I'm trying to read large raw images using the RandomAccessFile. Different images are of different types, some are uInt8, some are int8, some are int16, uInt16, float, etc. The only way I know to read them fast enough is by reading an array of bytes, and then putting the bits together into a new array of the desired type, e.g. shifting and adding to the bytes.
I'm sure there's a clever way to read different types really fast... How?Well... Is there any possabilities to create a new
int[] array that is "pointing" at the same memory
allocation as the byte[], just as you can do in C or
other languages with pointers?
Nope, Java is type safe.
It would be easy if I could make the compiler
interpret the byte[] as an int[]... Suggestions?
Create a java.io.DataInputStream to read from a java.io.ByteArrayInputStream that reads from your byte[] is one option:ByteArrayInputStream byteStream = ByteArrayInputStream(anArrayOfBytes);
DataInputStream integerStream = new DataInputStream(byteStream);
int firstInt = integerStream.readInt();
...If you need random access to an int array maybe you need to create the array first and the read ints to it... -
Byte[] into StringBuffer ?
This is what I've got:
new StringBuffer(new String(myByteArray));
Is this the best way of getting a byte[] into a StringBuffer, or will it suffer from converting it to a String first ? (likely to be between 1,000 and 50,000 bytes in the array).
Annoyingly, there is no append(byte[]) method in StringBuffer, and you can't cast the byte[] into a char[]. grr.Either create a char[] array of the same size of the byte[] array and copy the elements:
char[] c = new char[b.length];
for (int i = 0; i < b.length; i++) {
c[i] = (char)(b[i] & 0xFF);
}Or convert it to a String (takes a little longer, and StringBuffer will get the chars from it). Just use the right encoding, or you might get "false" String values:
String s = new String(b, "ISO8859_1");The character encoding ISO 8859-1, will make a one to one mapping between bytes and characters. -
Combine Columns From Separate Arrays Into One Formatted Table
What I'm trying to do is make two WMI queries with 2 different classes for a list of machines and then patch the columns together into one single array that is formatted as a table with columns and rows. I seem to keep banging my head against the wall and
I can't help but feel that the answer is simple. I can certainly create an array that contains all 3 columns (such as in the commented out part) but no matter which angle I go at it, it always seems to end up as all the data in one single row in each column
rather than a nicely formatted table. I've even tried constructing separate custom objects and adding the different objects to the array but that's obviously not working. Below is the code of the last thing I tried. I need someone to bash it to death and tell
me the (most likely obvious) thing that I'm doing wrong. Thanks!
$failedos = @()
$failedcs = @()
$ccs = get-adcomputer -property operatingsystem -filter {name -like "*-CC*"} | select name | sort name
$cs = foreach ($cc in $ccs){$cc.name | % {if ($c=get-wmiobject -computername $cc.name -class win32_computersystem -ErrorAction SilentlyContinue){$c | select @{Name="Name";Expression={$_.Name}}, @{Name="Model";Expression={$_.Model}}} else {$failedcs += "$_"}}}
$os = foreach ($cc in $ccs){$cc.name | % {if ($o=get-wmiobject -computername $cc.name -class win32_operatingsystem -ErrorAction SilentlyContinue){$o | select @{Name="OperatingSystem";Expression={$_.caption}}} else {$failedos += "$_"}}}
#[array]$osprops = @{'Name'=$cs.Name;'Model'=$cs.Model;'OperatingSystem'=$os.OperatingSystem}
$result = @()
Foreach ($Line in $cs) {
$MyCustomObject = New-Object -TypeName PSObject
Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Name" -Value $Line.name -Force
Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Model" -Value $Line.Model -Force
$result += $MyCustomObject
foreach ($Line2 in $os) {
$MyCustomObject2 = New-Object -TypeName PSObject
Add-Member -InputObject $MyCustomObject2 -MemberType NoteProperty -Name "OperatingSystem" -Value $Line2.OperatingSystem -Force
$result += $MyCustomObject2Any help?
$ccs = get-adcomputer -property operatingsystem -filter {name -like "*-CC*"} |
select -ExpandProperty name | sort
$Result =
Foreach ($CC in $CCs)
$Object =
New-Object PSObject -Property @{ Name = $CC
Model = 'Failed'
OperatingSystem = 'Failed'
Try {
$Object.Model =
get-wmiobject -computername $CC -class win32_computersystem -ErrorAction Stop |
select -ExpandProperty Model
$Object.OperatingSystem =
get-wmiobject -computername $CC -class win32_operatingsystem -ErrorAction Stop |
select -ExpandProperty Caption
Catch{}
Finally { $Object }
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " " -
Collecting data from multiple rows into one column
I'd like to run a query and put a collection of items into one output column instead of multiple rows. See the example below:
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Prod
PL/SQL Release 10.2.0.5.0 - Production
"CORE 10.2.0.5.0 Production"
TNS for 32-bit Windows: Version 10.2.0.5.0 - Production
NLSRTL Version 10.2.0.5.0 - Production
CREATE TABLE "SKIP"."INGREDIENTS"
( "INGRED_ID" NUMBER,
"INGRED_NAME" VARCHAR2(20 BYTE),
"STORES" VARCHAR2(20 BYTE)
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "USERS" ;
REM INSERTING into SKIP.INGREDIENTS
Insert into SKIP.INGREDIENTS (INGRED_ID,INGRED_NAME,STORES) values (1,'SEA SALT','Food lion');
Insert into SKIP.INGREDIENTS (INGRED_ID,INGRED_NAME,STORES) values (2,'TABLE SALT','Food lion');
Insert into SKIP.INGREDIENTS (INGRED_ID,INGRED_NAME,STORES) values (3,'FLOUR','Piggly Wiggly');
Insert into SKIP.INGREDIENTS (INGRED_ID,INGRED_NAME,STORES) values (4,'YEAST',null);
Insert into SKIP.INGREDIENTS (INGRED_ID,INGRED_NAME,STORES) values (5,'BEER','ABC Store');
CREATE TABLE "SKIP"."PRETZELS"
( "PRETZEL_ID" NUMBER,
"PRETZEL_NAME" VARCHAR2(20 BYTE),
"PRETZEL_DESC" VARCHAR2(100 BYTE)
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "USERS" ;
REM INSERTING into SKIP.PRETZELS
Insert into SKIP.PRETZELS (PRETZEL_ID,PRETZEL_NAME,PRETZEL_DESC) values (1,'CLASSIC','Classic knot pretzel');
Insert into SKIP.PRETZELS (PRETZEL_ID,PRETZEL_NAME,PRETZEL_DESC) values (2,'THICK STICK','Straight pretzel, abt 1/2" in dia');
CREATE TABLE "SKIP"."INGRED_XREF"
( "PRETZEL_ID" NUMBER,
"INGRED_ID" NUMBER
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "USERS" ;
REM INSERTING into SKIP.INGRED_XREF
Insert into SKIP.INGRED_XREF (PRETZEL_ID,INGRED_ID) values (1,1);
Insert into SKIP.INGRED_XREF (PRETZEL_ID,INGRED_ID) values (1,2);
Insert into SKIP.INGRED_XREF (PRETZEL_ID,INGRED_ID) values (1,4);
Insert into SKIP.INGRED_XREF (PRETZEL_ID,INGRED_ID) values (2,2);
Insert into SKIP.INGRED_XREF (PRETZEL_ID,INGRED_ID) values (2,3);
Insert into SKIP.INGRED_XREF (PRETZEL_ID,INGRED_ID) values (2,5);
-- Constraints for Table INGRED_XREF
ALTER TABLE "SKIP"."INGRED_XREF" MODIFY ("PRETZEL_ID" NOT NULL ENABLE);
ALTER TABLE "SKIP"."INGRED_XREF" MODIFY ("INGRED_ID" NOT NULL ENABLE);
{code}
Desired output (note how the ingredients are all listed in one column, separated by commas):
{code}
PRETZEL_ID PRETZEL_NAME PRETZEL_DESC INGREDIENTS
1 CLASSIC Classic knot pretzel SEA SALT, TABLE SALT, YEAST
2 THICK STICK Straight pretzel, abt 1/2" in dia TABLE_SALT, FLOUR, BEERSee the FAQ : {message:id=9360005}
Especially links concerning string aggregation. -
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){} } }
} -
Fetch data from two tables and insert into one table
I have similar to the following data in two tables (@Plant, @PlantDirector) and need to consolidate into one table (@PlantNew) as follows.
DECLARE @Plant TABLE (PlantID INT, PlantName VARCHAR(100))
INSERT INTO @Plant (PlantID, PlantName) VALUES (1, 'Name One'),(2, 'Name Two'),(3, 'Name Three'),(4, 'Name Four'),(5, 'Name Five'),(6, 'Name Six')
Director data for the Plants exist in the following table. Assistant value 1 means Assistant Director and 0 means Director.
Data exists only for subset of plants and a Plant may have one or both roles.
DECLARE @PlantDirector TABLE (PlantID INT, PlantDirectorID INT, Assistant bit)
INSERT INTO @PlantDirector (PlantID, PlantDirectorID, Assistant) VALUES (2, 111, 1),(2, 222, 0),(4, 333, 0),(6,444,1)
The above data needs to be inserted into one table (@PlantNew) as follows:
PlantID in @Plant table is IDENTITY value and needs to be inserted as-is into this table.
PlantDirExists will get a value of 1 if at least one record exists in @PlantDirector table for a PlantID. PlantAssistantDirID and PlantDirID should be set to the corresponding PlantDirID or NULL appropriately depending on the data.
DECLARE @PlantNew TABLE (PlantID INT, PlantName VARCHAR(100), PlantDirExists bit, PlantAssistantDirID INT, PlantDirID INT)
INSERT INTO @PlantNew (PlantID, PlantName, PlantDirExists, PlantAssistantDirID, PlantDirID)
VALUES (1, 'Name One', 0, NULL, NULL),(2, 'Name Two', 1, 111, 222),(3, 'Name Three', 0, NULL, NULL),(4, 'Name Four', 1, NULL, 333),(5, 'Name Five', 0, NULL, NULL),(6, 'Name Six',1, 444, NULL)
How do I achieve the above using SQL ? Thanks.like this
INSERT @PlantNew (PlantID, PlantName, PlantDirExists, PlantAssistantDirID, PlantDirID)
SELECT p.PlantID,
p.PlantName,
CASE WHEN pd.PlantID IS NULL THEN 0 ELSE 1 END,
PlantAssistantDirID,
PlantDirID
FROM @Plant p
LEFT JOIN (SELECT PlantID,
MAX(CASE WHEN Assistant = 1 THEN PlantDirectorID END) AS PlantAssistantDirID,
MAX(CASE WHEN Assistant = 0 THEN PlantDirectorID END) AS PlantDirID
@PlantDirector
GROUP BY PlantID)pd
ON pd.PlantID = p.PlantID
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
You're missing a FROM
insert into @PlantNew
SELECT p.PlantID,
p.PlantName,
CASE WHEN pd.PlantID IS NULL THEN 0 ELSE 1 END,
PlantAssistantDirID,
PlantDirID
FROM @Plant p
LEFT JOIN (SELECT PlantID,
MAX(CASE WHEN Assistant = 1 THEN PlantDirectorID END) AS PlantAssistantDirID,
MAX(CASE WHEN Assistant = 0 THEN PlantDirectorID END) AS PlantDirID
from @PlantDirector
GROUP BY PlantID)pd
ON pd.PlantID = p.PlantID -
What is the efficient way of insert some bytes into a file?
Hello, everyone:
If I want to insert some bytes into a file (for example, insert the bytes before all the original content of the file, or append the bytes to a file), and the size of the original file is very big. I am wondering what is the efficient way? Where can I get some sample codes?
regards,
GeorgeThanks, DrClap.
I have tried your method and you are correct. I have written a simple program which can be used to insert "Hello World " to the start of a file ("c:\\temp\\input.txt"), and I have verified that it can work. Please help to see whether it is correct and whether it has a more efficient way.
public class TestDriver {
public static void main(String[] args) {
byte[] back_buffer = new byte [1024];
byte[] write_buffer = new byte [1024];
System.arraycopy("Hello World".getBytes(), 0, write_buffer, 0, "Hello World".getBytes().length);
int write_buffer_length = "Hello World ".getBytes().length;
int count = 0;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream (new File("c:\\temp\\input.txt"));
fos = new FileOutputStream (new File("c:\\temp\\output.txt"));
while ((count = fis.read (back_buffer)) >= 0)
fos.write(write_buffer, 0, write_buffer_length);
System.arraycopy (back_buffer, 0, write_buffer, 0, count);
write_buffer_length = count;
//write the last block
fos.write(write_buffer, 0, write_buffer_length);
fis.close();
fos.close();
//copy content back into original file
fis = new FileInputStream (new File("c:\\temp\\output.txt"));
fos = new FileOutputStream (new File("c:\\temp\\input.txt"));
while ((count = fis.read (back_buffer)) >= 0)
fos.write(back_buffer, 0, count);
fis.close();
fos.close();
//remove temporary file
File f = new File ("c:\\temp\\output.txt");
f.delete();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
fis.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
try {
fos.close();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
fis.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
try {
fos.close();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}regards,
George
Maybe you are looking for
-
HP Pavilion dv6-1106ax recovery disk
Hi, I've had to replace my hard drive and was wondering if you could provide the recovery disk? I have a HP Pavilion dv6-1106ax notebook and runs on Vista Home 32bit. Any help would be much appreciated Thanks
-
Anyone know why my feed is not showing online? It works locally and it used to work online. I didn't change any code and all of sudden its giving me this error. MM_XSLTransform error. Transformation Error. Security access denied (coldfusion.runtime.F
-
Mac Mini (mid 2010) 4GB + Windows 7 boot issue
Afternoon, In februari I've asked the same question, and I still haven't figured out what the issue is. Figured it wouldn't be bad to fire up de discussion again; perhaps there are some new suggestions. Hi folks, I have the following issue with my 20
-
We are a 1:1 iPad school with iPad 2. I'm trying to update iOS to 8.2 and updating all apps as needed. When I plug in a previously supervised iPad, Configurator immediately goes into restore mode and wipes it clean and sets it up ready to "prepare" e
-
Upgrade my old Tandberg MXP 6000, 3000 and 880
I have to 3 Question 1. I am trying to download upgrade to F9.1 or higher for Tandberg MXP 6000, 3000 and 880 2. Is there any instruction on how to install them 3. and do I need a license Key for it.