Read bits from a file to a string???
Is it possible to read a file using som sort of InputStream and take 2 bits at a time and puting them to a string... The string should then hold 00, 01, 10 or 11
all help will be appreciated
/Eric
Of course you can convert the integer n returned by the method read() into a binary String through
String binaryString = Integer.toBinaryString(n);//n is the returned int
Similar Messages
-
How to read bits from the file?
Hello everybody,
I'm beginner in LabVIEW. I need to get bits from the file, but I don't know how I can do it. I use the example "Read Binary File VI" from LabVIEW Help, but it returns DBL array. And for a long time I can't find a solution to convert this array to array of bits. Can somebody help me? Thanks in advance.
Solved!
Go to Solution.tranonim wrote:
Hello everybody,
I'm beginner in LabVIEW. I need to get bits from the file, but I don't know how I can do it. I use the example "Read Binary File VI" from LabVIEW Help, but it returns DBL array. And for a long time I can't find a solution to convert this array to array of bits. Can somebody help me? Thanks in advance.
You can pass in the type into the Read Binary File VI to get the data in whatever form you want. Just remember that a boolean is really 8 bits.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
Reading data from flat file Using TEXT_IO
Dear Gurus
I already posted this question but this time i need some other changes .....Sorry for that ..
I am using 10G forms and using TEXT_IO for reading data from flat file ..
My data is like this :-
0|BP-V1|20100928|01|1|2430962.89|27|2430962.89|MUR|20100928120106
9|2430962.89|000111111111|
1|61304.88|000014104113|
1|41961.73|000022096086|
1|38475.65|000023640081|
1|49749.34|000032133154|
1|35572.46|000033093377|
1|246671.01|000042148111|
Here each column is separated by | . I want to read all the columns and want to do some validation .
How can i do ?
Initially my requirement was to read only 2 or 3 columns so i did like this ...
Procedure Pay_Simulator(lfile_type varchar2,lac_no varchar2,lcur varchar2,lno_item number,ltotal number,ldate date,lpay_purp varchar2,lfile_name varchar2)
IS
v_handle utl_file.file_type;
v_filebuffer varchar2(500);
line_0_date VARCHAR2 (10);
line_0_Purp VARCHAR2 (10);
line_0_count Number;
line_0_sum number(12,2);
line_0_ccy Varchar2(3);
line_9_sum Number(12,2);
line_9_Acc_no Varchar2(12);
Line_1_Sum Number(12,2);
Line_1_tot Number(15,2) := 0;
Line_1_flag Number := 0;
lval number;
lacno varchar2(16);
v_file varchar2(20);
v_path varchar2(50);
Begin
v_file := mcb_simulator_pkg.GET_FILENAME(lfile_name); -- For the file name
v_path :=rtrim(regexp_substr( lfile_name , '.*\\' ),'\'); For the Path
v_path := SUBSTR (lfile_name,0, INSTR (lfile_name, '\', -1));
v_handle := UTL_FILE.fopen (v_path, v_file, 'r');
LOOP
UTL_FILE.get_line (v_handle, v_filebuffer);
IF SUBSTR (v_filebuffer, 0, 1) = '0' THEN
SELECT line_0 INTO line_0_date
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_0, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 3;
SELECT line_0 INTO line_0_Purp
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_0, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 4;
SELECT line_0 INTO line_0_count
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_0, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 7;
SELECT line_0 INTO line_0_sum
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_0, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 8;
SELECT line_0 INTO line_0_ccy
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_0, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 9;
ELSIF SUBSTR (v_filebuffer, 0, 1) = '9' THEN
SELECT line_9 INTO line_9_Acc_no
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_9, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 3;
SELECT line_9 INTO line_9_sum
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_9, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 2;
ELSIF SUBSTR (v_filebuffer, 0, 1) = '1' THEN
line_1_flag := line_1_flag+1;
SELECT line_1 INTO line_1_sum
FROM (SELECT LTRIM (REGEXP_SUBSTR (v_filebuffer, '[^|]+{1}', 1, LEVEL)) line_1, ROWNUM rn
FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (v_filebuffer, '[^|]*')) + 1)
WHERE rn = 3;
Line_1_tot := Line_1_tot + line_1_sum;
END IF;
END LOOP;
DBMS_OUTPUT.put_line (Line_1_tot);
DBMS_OUTPUT.PUT_LINE (Line_1_flag);
UTL_FILE.fclose (v_handle);
END;
But now how can i do ? Shall i use like this select Statement for all the columns ?Sorry for that ..
As per our requirement ...
I need to read the flat file and it looks like like this .
*0|BP-V1|20100928|01|1|2430962.89|9|2430962.89|MUR|20100928120106*
*9|2430962.89|000111111111|*
*1|61304.88|000014104113|*
*1|41961.73|000022096086|*
*1|38475.65|000023640081|*
*1|49749.34|000032133154|*
*1|35572.46|000033093377|*
*1|246671.01|000042148111|*
*1|120737.25|000053101979|*
*1|151898.79|000082139768|*
*1|84182.34|000082485593|*
I have to check the file :-
Validation are 1st line should start from 0 else it should raise an error and insert that error into one table .
The for 2nd line also same thing ..it should start from 9 else it should raise an error and insert that error into one table .
Then the 3rd line should start from 1 else it should raise an error and insert that error into one table .
After that i have to do a validation like i will read the 1st line 2nd column .. It should be like this BP-V1 else raise an error and insert that error to a table . Then i will check the 3rd column which is 20100928 , it should be YYYYMMDD format else same thing ERROR.
Then like this for all columns i have different validation .......
Then it will check for the 2nd line 3rd column . this is an account no .1st i will check it should be 12 char else ERROR .Then I will check that what user has imputed in the form.Like for example User putted 111111111 then i will check with this 000111111111 which is there in the 2nd line . I have to add 000 before that Account no which user imputed .
Then the lines which is starting from 1 , i have to take all the 2nd column for all the lines which is starting from 1 and i have to do a sum . After that i have to compare that sum with the value in the 1st lines ( Starting from 0) 6th column . It should be same else ERROR ...
Then same way i have to count all the lines which is starting from 1 . Then i have to compare with the 7th column of 1st line . It should be same . Here in this file it should be 9.
MY CODE IS :-
Procedure Pay_Simulator(lfile_type varchar2,lac_no varchar2,lcur varchar2,lno_item number,ltotal number,ldate date,lpay_purp varchar2,lfile_name varchar2)
IS
v_handle TEXT_IO.file_type;
v_filebuffer varchar2(500);
line_0_date VARCHAR2 (10);
line_0_Purp VARCHAR2 (10);
line_0_count Number;
line_0_sum number(12,2);
line_0_ccy Varchar2(3);
line_9_sum Number(12,2);
line_9_Acc_no Varchar2(12);
Line_1_Sum Number(12,2);
Line_1_tot Number(15,2) := 0;
Line_1_flag Number := 0;
lval number;
lacno varchar2(16);
v_file varchar2(20);
v_path varchar2(50);
LC$String VARCHAR2(50) ;--:= 'one|two|three|four|five|six|seven' ;
LC$Token VARCHAR2(100) ;
i PLS_INTEGER := 2 ;
lfirst_char number;
lvalue Varchar2(100) ;
Begin
v_file := mcb_simulator_pkg.GET_FILENAME(lfile_name); For the file name
v_path :=rtrim(regexp_substr( lfile_name , '.*\\' ),'\'); For the Path
--v_path := SUBSTR (lfile_name,0, INSTR (lfile_name, '\', -1));
Message(lfile_name);
v_handle := TEXT_IO.fopen(lfile_name, 'r');
BEGIN
LOOP
TEXT_IO.get_line (v_handle, v_filebuffer);
lfirst_char := Substr(v_filebuffer,0,1);
--Message('First Char '||lfirst_char);
IF lfirst_char = '0' Then
Loop
LC$Token := mcb_simulator_pkg.Split( v_filebuffer, i , '|') ;
Message('VAL - '||LC$Token);
lvalue := LC$Token;
EXIT WHEN LC$Token IS NULL ;
i := i + 1 ;
End Loop;
Else
Insert into MU_SIMULATOR_output_ERR (load_no,ERR_CODE,ERR_DESC) values (9999,'0002','First line should always start with 0');
Forms_DDL('Commit');
raise form_Trigger_failure;
End if ;
TEXT_IO.get_line (v_handle, v_filebuffer);
lfirst_char := Substr(v_filebuffer,0,1);
LC$Token := mcb_simulator_pkg.Split( v_filebuffer, i , '|') ;
--Message('Row '||LC$Token);
IF lfirst_char = '9' Then
Null;
Else
Insert into MU_SIMULATOR_output_ERR (load_no,ERR_CODE,ERR_DESC) values (8888,'0016','Second line should start with 9');
Forms_DDL('Commit');
raise form_Trigger_failure;
End IF;
LOOP
TEXT_IO.get_line (v_handle, v_filebuffer);
lfirst_char := Substr(v_filebuffer,0,1);
LC$Token := mcb_simulator_pkg.Split( v_filebuffer, i , '|') ;
--Message('Row '||LC$Token);
IF lfirst_char = '1' Then
Null;
Else
Insert into MU_SIMULATOR_output_ERR (load_no,ERR_CODE,ERR_DESC) values (7777,'0022','The third line onward should start with 1');
Forms_DDL('Commit');
raise form_Trigger_failure;
End if;
END LOOP;
--END IF;
END LOOP;
EXCEPTION
When No_Data_Found Then
TEXT_IO.fclose (v_handle);
END;
Exception
When Others Then
Message('Other error');
END;
I am calling the FUNCTION which you gave SPLIT as mcb_simulator_pkg.Split. -
Read data from Excel file and diaplay in Webdynpro
Hi all,
I need some help. I have a Excel file with set of name, phonenumbers . I want to know how to display the data using Webdynpro. Could some one help me. help is appreciated and I promise to award points for right answer.
Thank you
Maruti<b>Hi
i can explain you to read data from Excel file
First You have to download the jxl.jar file. You can get this file from the Below site
</b><a href="http://www.andykhan.com/jexcelapi/download.html">jexcelapi jar</a>
It will be in Compressed Fromat So Unzip it to get the Contents
After Unzipping The File You will get a Folder (jexcelapi/jxl.jar)
Now in NWDS open web dynpro explorer, Right Click Your Project, a popup menu will appear and in that click Properties
You will get window displaying your Project Properties
On Left Side of the window You Will Find "Java Build Path"
Click That "Java Build Path" and you will get 4 Tabs Showing ( Source,Projects,Libraries,Order and Export)
Click Libraries Tab
You will find options many options buttons
In that click the Button "Add External Jars"
You will get Window in order to fecth the jxl.jar file from the location you had stored
After selecting the jxl.jar i will get displayed and click ok
Now Open Navigator
Open Your Project
You will find Lib folder
Copy the jxl.jar to that lib folder
Note : You cannot Read the Content from the excel file directly
First You Have to copy that file to the Server,
And from the Server you can get the file absolute path
With the absolute path you can read the contents of the Excel file
You have to save the Excel file as .xls Format and Not as xlsx format i will not accept that...
You have Upload the Excel file from the Server Using the File Upload UI Element
This Coding will extract 3 columns from the Xls File
Coding
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import com.sap.fileupload.wdp.IPrivateFileUpload_View;
import com.sap.tc.webdynpro.services.sal.datatransport.api.IWDResource;
public void onActionUpload_File(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionUpload_File(ServerEvent)
IPrivateFileUpload_View.IContextElement element1 = wdContext.currentContextElement();
IWDResource resource = element1.getFileResource();
element1.setFileName(resource.getResourceName());
element1.setFileExtension(resource.getResourceType().getFileExtension());
//@@end
public void onActionUpload_File_in_Server(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionUpload_File_in_Server(ServerEvent)
InputStream text=null;
int temp=0;
try
File file = new File(wdContext.currentContextElement().getFileResource().getResourceName().toString());
FileOutputStream op = new FileOutputStream(file);
if(wdContext.currentContextElement().getFileResource()!=null)
text=wdContext.currentContextElement().getFileResource().read(false);
while((temp=text.read())!=-1)
op.write(temp);
op.flush();
op.close();
path = file.getAbsolutePath();
wdComponentAPI.getMessageManager().reportSuccess(path);
catch(Exception e)
e.printStackTrace();
//@@end
public void onActionUpload_Data_into_Table(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionUpload_Data_into_Table(ServerEvent)
try
Workbook wb =Workbook.getWorkbook(new File(path));
Sheet sh = wb.getSheet(0);
//wdComponentAPI.getMessageManager().reportSuccess("Columns = "+sh.getColumns());
//wdComponentAPI.getMessageManager().reportSuccess("Rows = "+sh.getRows());
int columns = sh.getColumns();
int rows = sh.getRows();
int i=0;
for(int j=1;j<=rows;j++)
ele=wdContext.nodeTable_Data().createTable_DataElement();
Cell c1 = sh.getCell(i,j);
ele.setTab_Name(c1.getContents());
Cell c2 = sh.getCell(i+1,j);
ele.setTab_Degree(c2.getContents());
Cell c3 = sh.getCell(i+2,j);
ele.setTab_Percentage(c3.getContents());
wdContext.nodeTable_Data().addElement(ele);
catch(Exception ex)
wdComponentAPI.getMessageManager().reportSuccess(ex.toString());
//@@end
* The following code section can be used for any Java code that is
* not to be visible to other controllers/views or that contains constructs
* currently not supported directly by Web Dynpro (such as inner classes or
* member variables etc.). </p>
* Note: The content of this section is in no way managed/controlled
* by the Web Dynpro Designtime or the Web Dynpro Runtime.
//@@begin others
String path;
IPrivateFileUpload_View.ITable_DataElement ele;
//@@end
Regards
Chandran S -
How to read HyperLinks from pdf file??
hi developer's,
I am in PDF processing... I am having doubt in that Processing.
How to read Hyperlinks from PDF file?
I can able to set the hyperlink.. But i cant able to get the hyperlinks..
The following example program will set the hyperlink to the PDF file using lowagie API..
import com.lowagie.text.Anchor;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.HtmlWriter;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
public class Argu1 {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter pdf = PdfWriter.getInstance(document,
new FileOutputStream("PageLink.pdf"));
PdfReader pdf_read=new
document.open();
document.add(new Paragraph("Hi Everbody....!"));
Anchor pdfRef = new Anchor("Click Me");
pdfRef.setReference("www.java2s.com");
Anchor rtfRef = new Anchor("Touch Me");
rtfRef.setReference("www.sun.com");
System.out.println(rtfRef.reference());
document.add(pdfRef);
document.add(Chunk.NEWLINE);
document.add(rtfRef);
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
document.close();
Help me how to read the Hyperlinks from the PDF file using java ...
Thanks in advance,
With Regards,
J.ImranInstead of cross-posting unformatted code you could have taken a look at the API, because there you might have come across a method named getLinks...Even though it's not documented, I really suspect that it will return the Hyperlinks on a given page.
-
Hi Guys,
I am trying to read data from a CSV file character by character. Whats the best way to do this? Any examples around?
Thanks
tzafDoes this mean your file will have multiple lines? And each line would indicate a new record? If so, you should use the BufferedReader and take in each line as a String. Then you can use the StringTokenizer to separate your string into tokens using the comma as your delimiter. From there you can convert the string tokens into whatever form you like, but by default they are already in String form. To make it an Integer I'd use Integer.parseInt().
I will show you some code on how to get the values from your file using the BufferedReader and the StringTokenizer but what you do with those values afterwards I'm going to leave up to you.
File csvfile = new File("myfile.csv");
byte[] fileBuf = new byte[1024]; // buffer for file data
int bytesRead = 0; // number of bytes read
try
BufferedReader fileIn = new BufferedReader( new FileReader( csvfile ));
PrintStream out = new PrintStream( System.out );
String readLine; // stores a line from the file as a string
while( (readLine = fileIn.readLine()) != null )
StringTokenizer tokens = new StringTokenizer( readLine, ",", false);
// false means you don't want to count the commas, only the values
while( tokens.hasMoreTokens() )
String aValue = tokens.nextToken();
// ... do what you want with the value
// ... change to Integer or whatever
out.println(aValue); // Printing the value to the screen
fileIn.close();
}Good luck,
.kim -
To read data from exel file into sap
hi all,
How to read data from exel file into the internal table in abap?
Regards,
sugeet.Hi Sugeet,
Use the following code.
DATA : BEGIN OF tbl_asset occurs 0,
anlkl LIKE anla-anlkl, " Asset Class
bukrs LIKE anla-bukrs, " Company Code
ranl1 LIKE ra02s-ranl1, " Asset #
txt50 LIKE anla-txt50, " Description 1
txa50 LIKE anla-txa50, " Description 2
sernr LIKE anla-sernr, " Serial #
invnr LIKE anla-invnr, " Inventory #
menge LIKE anla-menge, " Quantity
meins LIKE anla-meins, " Base UOM
inken LIKE anla-inken, " Inventory
END OF tbl_asset.
DATA : w_filename TYPE IBIPPARMS-path,
w_file TYPE string.
start-of-selection.
*popup for file path from user
CALL FUNCTION 'F4_FILENAME'
EXPORTING
PROGRAM_NAME = SYST-CPROG
DYNPRO_NUMBER = SYST-DYNNR
IMPORTING
FILE_NAME = w_filename .
MOVE w_filename TO w_file .
* upload data
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
FILENAME = w_file
FILETYPE = 'ASC'
HAS_FIELD_SEPARATOR = 'X'
TABLES
DATA_TAB = tbl_asset
EXCEPTIONS
FILE_OPEN_ERROR = 1
FILE_READ_ERROR = 2
NO_BATCH = 3
GUI_REFUSE_FILETRANSFER = 4
INVALID_TYPE = 5
NO_AUTHORITY = 6
UNKNOWN_ERROR = 7
BAD_DATA_FORMAT = 8
HEADER_NOT_ALLOWED = 9
SEPARATOR_NOT_ALLOWED = 10
HEADER_TOO_LONG = 11
UNKNOWN_DP_ERROR = 12
ACCESS_DENIED = 13
DP_OUT_OF_MEMORY = 14
DISK_FULL = 15
DP_TIMEOUT = 16
OTHERS = 17
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
for HAS_FIELD_SEPARATOR Use
'X': Fields are separated by tabs.
SPACE: Fields are not separated by tabs. In this case, the table must contain only one column or all columns must be contained in the file in their entire length.
Hope it helps...
Lokesh
Pls. reward appropriate points -
How to continue to read Object from a file?
At some program I write an object into a file. This program will be called again and again so that there are many objects which are saved to that file. And I write another program to read object from this file. I can read the first object but can not read the second. However if I delete the object in that file (using editplus, by manually) I can read the second. Because now the second object is the first object. (Delete first object).
The exception when I read the second object is below:
java.io.StreamCorruptedException: Type code out of range, is -84
at java.io.ObjectInputStream.peekCode(ObjectInputStream.java:1607)
at java.io.ObjectInputStream.refill(ObjectInputStream.java:1735)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:272)
at LogParser.main(LogParser.java:42)
Exception in thread "main" The read object from file program is below:
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(path + File.separator + "ErrorApp21config2.log");
ObjectInputStream ois = new ObjectInputStream(fis);
ErrorLog errorLog = (ErrorLog)ois.readObject();
System.out.println(errorLog.getErrorDate());
FIFData fifData = (FIFData)errorLog.getErrorDescription();
CommRegistration commRegistration = (CommRegistration)
fifData.getDataObject(FIFData.REGISTRATION_DATA);
String ic = commRegistration.getPatient().getPatExtID();
System.out.println(ic);
CommQueue commQueue = (CommQueue) fifData.getDataObject(FIFData.QMS_DATA);
String location = commQueue.getLocation();
System.out.println(location);
ois.readObject(); //will throw above exception
fis.close();
}Can anyone tell me how to continue to read object? Or I should do some special things when I write object into file?Thanks Jos.
Perhaps you are correct.
There are some code in a SessionBean to log an object. Write file code is below.
private void logPreRegError(
byte[] strOldFifData,
byte[] strNewFifData,
String requestID)
throws TTSHException {
if (requestID.equals(RequestConstants.ADMIT_PATIENT)){
String runtimeProp = System.getProperty("runtimeproppath");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(
runtimeProp + File.separator + "Error.log", true);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(strOldFifData);
bos.write(strNewFifData);
bos.flush();
} catch (FileNotFoundException e) {
log(e);
} catch (IOException e) {
log(e);
} finally{
if (fos != null){
try {
fos.close();
} catch (IOException e1) {
log(e1);
}strOldFifData and strNewFifData are the byte[] of an object. Below is the code to convert object to byte[].
private byte[] getErrorData(FIFData fifData, boolean beforeException, String requestID) {
ErrorLog errorLog = new ErrorLog();
errorLog.setErrorDate(new Date());
errorLog.setErrorDescription(fifData);
errorLog.setErrorModule("Pre Reg");
if (beforeException){
errorLog.setErrorSummary("RequestID = " + requestID +" Before Exception");
}else{
errorLog.setErrorSummary("RequestID = " + requestID +" After Exception");
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
byte[] bytErrorLog = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(errorLog);
oos.flush();
bytErrorLog = baos.toByteArray();
} catch (IOException e) {
log(e);
} finally {
if (baos != null){
try {
baos.close();
} catch (IOException e1) {
log(e1);
return bytErrorLog;
}I have two questions. First is currently I have got the log file generated by above code. Is there any way to continue to read object from log file?
If can't, the second question is how to write object to file in such suitation (SessionBean) so that I can continue to read object in the future? -
Hello everybody,
I try to read arabic unicode signs from a file into a String within my program.
I create the file using simple windows notepad.
The sign Im wrinting look perfectly arabic (although I actually cant read it).
Now when I start my program and read the signs it doesnt read arabic signs but signs that are within the Unicode range 0000 - 00FF wich is Latin + Latin-1 Supplement.
But I expect the sign beeing somewhere arround 0600 - 06FF.
I have the feeling its realated to a codepage or encodeing thing, but I dont really know a lot about it.
Can you somehow help me?
Do you need more information?
Can you tell me where I can get some usefull information?
Thank you!
StefanOK, here is the code
private static ArrayList<String> readLinesFromFile(File file){
ArrayList<String> toReturn = new ArrayList<String>();
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
toReturn.add(line);
} catch (FileNotFoundException e) {
e.printStackTrace();
return toReturn;
} -
Read data from xml files and populate internal table
Hi.
How to read data from xml files into internal tables?
Can u tell me the classes and methods to read xml data..
Can u explain it with a sample program...<pre>DATA itab_accontextdir TYPE TABLE OF ACCONTEXTDIR.
DATA struct_accontextdir LIKE LINE OF itab_accontextdir.
DATA l_o_error TYPE REF TO cx_root.
DATA: filename type string ,
xmldata type xstring .
DATA: mr TYPE REF TO if_mr_api.
mr = cl_mime_repository_api=>get_api( ).
mr->get( EXPORTING i_url = 'SAP/PUBLIC/BC/xml_files_accontext/xml_accontextdir.xml'
IMPORTING e_content = xmldata ).
WRITE xmldata.
TRY.
CALL TRANSFORMATION id
SOURCE XML xmldata
RESULT shiva = itab_accontextdir.
CATCH cx_root INTO l_o_error.
ENDTRY.
LOOP AT itab_accontextdir INTO struct_accontextdir.
WRITE: / struct_accontextdir-context_id,
struct_accontextdir-context_name,
struct_accontextdir-context_type.
NEW-LINE.
ENDLOOP.</pre>
<br/>
Description:
In the above code snippet I am storing the data in an xml file(you know xml is used to store and transport data ) called 'xml_accontextdir.xml' that is uploaded into the MIME repository at path 'SAP/PUBLIC/BC/xml_files_accontext/xml_accontextdir.xml'.
The below API is used to read a file in MIME repo and convert it into a string that is stored in ' xmldata'. (This is just a raw data that is got by appending the each line of xml file).
mr = cl_mime_repository_api=>get_api( ).
mr->get( EXPORTING i_url = 'SAP/PUBLIC/BC/xml_files_accontext/xml_accontextdir.xml'
IMPORTING e_content = xmldata ).
Once the 'xmldata' string is available we use the tranformation to parse the xml string that we have got from the above API and convert it into the internal table.
<pre>TRY.
CALL TRANSFORMATION id
SOURCE XML xmldata
RESULT shiva = itab_accontextdir.
CATCH cx_root INTO l_o_error.
ENDTRY.</pre>
Here the trasnsformation 'id ' is used to conververt the source xml 'xmldata' to resulting internal table itab_accontextdir, that have same structure as our xml file 'xml_accontextdir.xml'. In the RESULT root of the xml file has to be specified. (In my the root is 'shiva').
Things to be taken care:
One of the major problem that occurs when reading the xml file is 'format not compatible with the internal table' that you are reading into internal table. Iin order to get rid of this issue use one more tranformation to convert the data from the internal table into the xml file.
<pre>TRY.
CALL TRANSFORMATION id
SOURCE shiv = t_internal_tab
RESULT XML xml.
CATCH cx_root INTO l_o_error.
ENDTRY.
WRITE xml.
NEW-LINE.</pre>
<br/>
This is the same transformation that we used above but the differnce is that the SOURCE and RESULT parameters are changed the source is now the internal table and result is *xml *string. Use xml browser that is available with the ABAP workbench to read the xml string displayed with proper indentation. In this way we get the format of xml file to be used that is compatable with the given internal table.
Thank you, Hope this will help you!!!
Edited by: Shiva Prasad L on Jun 15, 2009 7:30 AM
Edited by: Shiva Prasad L on Jun 15, 2009 11:56 AM
Edited by: Shiva Prasad L on Jun 15, 2009 12:06 PM -
With "ApartmentFileHandler" I can write Apartment-objects to a file and read them from a file.
To write I loop through each room in the apartment and write its size
and type. I put 1 Room per line.
To read I read each line of the file and recreate the room stored
there. When there are no lines left in the file I pass the Rooms from
the file to the Apartment constructor and return the new Apartment.
Only one Apartment is stored in each file. (Apartment doesn?t implement
Serializable, so I cant write straight Apartment-objects to a file.)
So in the file, there are stored one "Room" per line: String type,
double size
QUESTION: How am I able to read all lines: first line first -> make a new room of
it, and store to a roomArray? Then second -> do same as I did to the
first.
Now my read()-method doesn't read all lines. How to change it to read next line?
Thanks in advance.
public class Room extends Space
public Room(String type, double area)
public String getType()
public double getSize()
public class Apartment extends Space
public static final String KITCHEN
public Apartment(Room[] rooms)
public String getType()
public double getSize()
public Room[] getRooms()
public class ApartmentFileHandler extends Object {
private FileOutputStream ostream;
private ObjectOutputStream op;
private FileInputStream istream;
private ObjectInputStream ip;
private String filepath;
public ApartmentFileHandler (String filepath) {
this.filepath = filepath;
public Apartment read()
throws InvalidApartmentFile,
IOException {
istream = new FileInputStream(filepath);
ip = new ObjectInputStream(istream);
// count how many rows in the file ie. rooms
String lineThatIsRead = ip.readLine();
int count =0;
while (lineThatIsRead != null) {
count =count +1;
lineThatIsRead =ip.readLine();
Room room;
Room roomArray[ ] = new Room[count];
for(int i =0; i<count; i++) {
String type =ip.readUTF();
double size =ip.readDouble();
room =new Room(type, size);
roomArray[ i ] =room;
Apartment apartment = new Apartment(roomArray);
return apartment;
public void write(Apartment apartment)
throws IOException {
ostream = new FileOutputStream(filepath);
op = new ObjectOutputStream(ostream);
int numberOfRooms =apartment.getRooms().length;
Room[] allRooms =apartment.getRooms();
for (int i=0; i< numberOfRooms; i++) {
op.writeUTF( allRooms[ i ].getType() );
op.writeDouble( allRooms[ i ].getSize() );
op.writeChars("\n");Hi,
I recommend using java.io.BufferedReader in conjunction with java.io.FileReader:
BufferedReader reader=new BufferedReader(new FileReader(filepath));
java.io.BufferedReader provides the method public java.lang.String readLine() throws java.io.IOException which lets you read a complete line from the underlying java.io.Reader object. Furthermore, BufferedReader will - as the name implies - buffer your IO-operations which will help you improve the program's performance. In order to read all the lines contained in a text file you might want to apply a loop:
String line;
while((line=reader.readLine())!=null && line.length()!=0){
//process data in string line (parse into string and double)
Of course, everything must be contained within a try-catch-block in order to be able to handle upcoming IOException objects.
Regards,
Michael -
Read lines from text file to java prog
how can I read lines from input file to java prog ?
I need to read from input text file, line after line
10x !If you search in THIS forum with e.g. read lines from file, you will find answers like this one:
Hi ! This is the answer for your query. This program prints as the output itself reading line by line.......
import java.io.*;
public class readfromfile
public static void main(String a[])
if you search in THIS forum, with e.g. read lines from text file
try{
BufferedReader br = new BufferedReader(new FileReader(new File("readfromfile.java")));
while(br.readLine() != null)
System.out.println(" line read :"+br.readLine());
}catch(Exception e)
e.printStackTrace();
} -
Apostroph and euro sign not read corectly from txt file
apostroph and euro sign not read corectly from txt file.
my code is like this:
FileInputStream fis= new FileInputStream(x+".html");
BufferedReader br=new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String Line="";
while ((Line = br.readLine()) != null) result+=Line;
br.close();
fis.close();
I use UTF-8 because the file contains also French characters.
What's the problem?
THANK YOU!apostroph and euro sign not read corectly from txt
file.
my code is like this:
FileInputStream fis= new FileInputStream(x+".html");
BufferedReader br=new BufferedReader(new
InputStreamReader(fis,"UTF-8"));
String Line="";
while ((Line = br.readLine()) != null) result+=Line;
br.close();
fis.close();
I use UTF-8 because the file contains also French
characters.
What's the problem?
THANK YOU!
This is from the FileInputStream API documentation:
FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. -
i am facing problem while reading values from properties file ...i am getting null pointer exception earlier i was using jdeveloper10g now i am using 11g
hi TimoHahn,
i am getting following exception in JDeveloper(11g release 2) Studio Edition Version 11.1.2.4.0 but it works perfectly fine in JDeveloper 10.1.2.1.0
Root cause of ServletException.
java.lang.NullPointerException
at java.util.PropertyResourceBundle.handleGetObject(PropertyResourceBundle.java:136)
at java.util.ResourceBundle.getObject(ResourceBundle.java:368)
at java.util.ResourceBundle.getString(ResourceBundle.java:334)
at org.rbi.cefa.master.actionclass.UserAction.execute(UserAction.java:163)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:119)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:315)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:442)
at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:103)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:171)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:139)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:178) -
How to read data from a file in OSB
hi guys,
Recently, I've got a problem with reading file from specific location. I've actually followed this post OSB 11g - Read or Poll File in OSB - Oracle Fusion Middleware Blog, and then
I know how to read a file. However, it does not as expected. Because, I've found no way to read data from the file. Therefore, no chance to manipulate the data like assigning to a variable, or extracting ....
Hence, is there any way to read data from file by using proxy service in OSB ??? No Java code ???
by the way, supposed that there is no way to read data from a file in OSB. So, What purposes will the way in the post above be used for?
Many thanks in advancehttp://jakarta.apache.org/poi/hssf/index.html
HSSF stands for Horrible Spreadsheet Format, but it still works!
Maybe you are looking for
-
How to update my list of bought products
a quick question how can I remove products from my app store list that I've downloaded for test purposes and removed from my Mac thx in advance for the info gr.Henny
-
Connect Timesten server remotely without using timesten client
I know it's a silly question but this is what i want to do:- I have my java application and I want to connect to the timesten server present on remote machine and moreover I don't have the permission to intall any Timesten Client or App server(weblog
-
Submit new record from search resutls
I would like to know how to submit the results from a search as a new record in the same table from which it came. Any thoughts??
-
have a MacBook Pro with Mac OS X 10.4.11 and need to upgrade to Mac OS X 10.5 to enable me to completely upgrade to latest version, however cannot find 10.5 to download...suggestions?
-
Schd. for delivery quantity in MMBE - Vl09
Dear We had one sales order which was having 375 quantity to be delivered. Also the same stock was available in the plant, storage location and batch. So we created delivery order through vl01n. Then for some reason we need reversed that delivery ord