Read contents of file into outputstream
Can anyone suggest that what are the best methods to read contents of a file (better cater to both conditions: big file size and small file size) into outputstream and send through socket...
Thanks.
Thanks for the answer. But I would like to ask the following question:
I have a VB application which generates a file. I have a Java application which read the contents of the file.
is it possible that VB side calls the read() (file) and send() (through socket to destination) methods in Java application once the file is generated? Actually my objective is VB is responsible for generating a file for Java application to read data from and then send the data (not file) to destination....If it is impossible to achieve, any alternative to achieve this?
Thanks
Edited by: whkhoo on Jun 15, 2008 8:45 PM
Similar Messages
-
Read contents of file into outputstream and send through socket
I have a file. Instead of transferring the whole file through socket to the destination, I will read the contents from the file (big or small file size) into outputstream and send them to the destination where the client will receive the data and directly display it....
Can you suggest any efficient way/methods to achieve that?
Thanks.I don' t understand what you think the difference is between those two techniques, but:
int count;
byte[] buffer = new byte[16384];
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
out.close();
in.close(); -
Sender File (FCC) - Content of File into single XML Tag
Hi,
Input file
This is Line1
This is Line2
Expected Sender File adapter FCC into XML
<Document>
.<File>
..<Content> This is line 1 This is line2</content>
.</File>
</Document>
FCC is giving the following output with the below config,
File.fieldNames = Content
File.fieldSeparator = '0x1A' (HexaDecimal rep for EndOfFile)
<Document>
.<File>
..<Content>This is line 1</content>
..<Content>This is line 2</content>
.</File>
</Document>
How can i read the complete file into a single XML tag?
I am aware of other options (AdapterModules or Javamapping). But i want to keep it simple to FileAdapter using FCC or using MessageTransformBean (if possible)
-SMFCC donse't work here, So i wrote a simple Java map inside Execute method to convert the content to the required format.
public void execute(InputStream in, OutputStream out) throws StreamTransformationException{
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
} finally {
in.close();
After i had the input string, i formatted it to get the required output as XML ...
<Document>
.<File>
..<Content> This is line 1 This is line2</content>
.</File>
</Document> -
Uploading the contents of file into custom table
Hi ,
I have a req where in i want to put the contents of the file into the Z table . I have taken a file upload UI element and in that i have taken 4 attributes as file name f, file type ,file size and file contents and binded this file contents to the data property of the UI element. Now with out explicitly defining the fields i want to put all this content of file into the Z table created for any file created or if i could put the whole text file into that table so that any one could see that file even though its not saved in the desktop for that user.
Can any one help me out?Yes i am converting it inot the lstring using the same FM which you have given. I have to store the total file but the only doubt is like if its a input field how could i save a file form. Can you please check the code i want to save the total file into the table.
DATA lo_nd_upload TYPE REF TO if_wd_context_node.
DATA lo_el_upload TYPE REF TO if_wd_context_element.
data i_data TYPE STANDARD TABLE OF string.
DATA ls_upload TYPE wd_this->Element_upload.
data lv_field type string.
data lt_file type TABLE OF ZFILE_UPLOAD.
data ls_file LIKE LINE OF lt_file.
data l_xstring type xstring.
data fields TYPE string_table.
data l_String type string.
navigate from <CONTEXT> to <UPLOAD> via lead selection
lo_nd_upload = wd_context->get_child_node( name = wd_this->wdctx_upload ).
@TODO handle non existant child
IF lo_nd_upload IS INITIAL.
ENDIF.
get element via lead selection
lo_el_upload = lo_nd_upload->get_element( ).
@TODO handle not set lead selection
IF lo_el_upload IS INITIAL.
ENDIF.
get all declared attributes
lo_el_upload->get_static_attributes(
IMPORTING
static_attributes = ls_upload ).
DATA lv_file_contents TYPE wd_this->Element_upload-file_contents.
navigate from <CONTEXT> to <UPLOAD> via lead selection
@TODO handle non existant child
IF lo_nd_upload IS INITIAL.
ENDIF.
get element via lead selection
lo_el_upload = lo_nd_upload->get_element( ).
alternative access via index
lo_el_upload = lo_nd_upload->get_element( index = 1 ).
@TODO handle not set lead selection
IF lo_el_upload IS INITIAL.
ENDIF.
get single attribute
lo_el_upload->get_attribute(
EXPORTING
name = 'FILE_CONTENTS'
IMPORTING
value = l_xstring ).
for text file conversion we have to FM
CALL FUNCTION 'HR_KR_XSTRING_TO_STRING'
EXPORTING
FROM_CODEPAGE = '8500'
IN_XSTRING = l_xstring
OUT_LEN =
IMPORTING
OUT_STRING = l_string.
SPLIT l_string AT cl_abap_char_utilities=>newline INTO TABLE i_data.
LOOP AT i_data INTO l_string.
SPLIT l_string AT cl_abap_char_utilities=>horizontal_tab INTO TABLE fields.
read TABLE fields into lv_field index 1.
endloop.
ls_upload will contain all the file details
ls_file-file_size = xstrlen( ls_upload-file_contents ) * lv_float .
ls_file-file_name = ls_upload-file_name.
ls_file-file_type = ls_upload-file_type.
ls_file-file_contents = ls_upload-file_contents.
insert ZFILE_UPLOAD FROM ls_file.
thanks -
Read an XML file into an ABAP program and manipulate it.
I would like to know if it is possible to do the following in an ABAP program:
1) Read an XML file into an ABAP internal table
2) Call an XSLT transformation on the source file and store the results in an ABAP table.
Is this possible to do? I have used ABAP XSLT in PI, but never in an ABAP program. I see you can use the CALL TRANSFORMATION command, but I have never used it in an ABAP program.
Kind Regards,
Tony.Check out these blogs.
XML DOM Processing in ABAP part I - Convert an ABAP table into XML file using SAP DOM Approach.
XML DOM Processing in ABAP part II - Convert an XML file into an ABAP table using SAP DOM Approach. -
How can i read local excel file into internal table in webdynpro for abap a
Could someone tell me how How can i read local excel file into an internal table in webdynpro for abap application.
thank u for your replyDeep,
File manuplations...............................
1. At the presentation level:
->GUI_UPLOAD
->GUI_DOWNLOAD
->CL_GUI_FRONTEND
2. At the application server level:
->OPEN DATASET : open a file in the application server for reading or writing.
->READ DATASET : used to read from a file on the application server that has been opened for reading
-> TRANSFER DATASET : writing data to a file.
-> CLOSE DATASET : closes the file
-> DELETE DATASET : delete file
If file is on the local PC,use the function module GUI_UPLOAD to upload it into an internal table by passing the given parameters......
call function 'GUI_UPLOAD'
exporting
filename = p_file
filetype = 'ASC'
has_field_separator = '#'
tables
data_tab = t_data
p_file : excel file path.
t_data : internal table
<b>reward points if useful.</b>
regards,
Vinod Samuel. -
Reading a flat file into Oracle
Can someone tell me the best way to read a flat file into Oracle8i?
You can use SQL*Loader
or programmatically with UTL_FILE package.
(Please see documentation of SQL*Loader
and using predefine package UTL_FILE) -
How do I read directly from file into byte array
I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
//Read File Contents into a Buffered Image
/** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
* (at least partially) a problem with non-standard colour models, which is why we set the
* destination colour model. The side effect should be standard colour model in subsequent reading.
BufferedImage bi = null;
ImageReader ir = null;
ImageInputStream stream = ImageIO.createImageInputStream(new File(path));
final Iterator i = ImageIO.getImageReaders(stream);
if (i.hasNext())
ir = (ImageReader) i.next();
ir.setInput(stream);
ImageReadParam param = ir.getDefaultReadParam();
ImageTypeSpecifier typeToUse = null;
for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
if (type.getColorModel().getColorSpace().isCS_sRGB())
typeToUse = type;
if (typeToUse != null)
param.setDestinationType(typeToUse);
bi = ir.read(0, param);
//ir.dispose(); seem to reference this in write
//stream.close();
//Write Buffered Image to Byte ArrayOutput Stream
if (bi != null)
//Convert to byte array
final ByteArrayOutputStream output = new ByteArrayOutputStream();
//Try and find corresponding writer for reader but if not possible
//we use JPG (which is always installed) instead.
final ImageWriter iw = ImageIO.getImageWriter(ir);
if (iw != null)
if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
MainWindow.logger.warning("Unable to Write Image");
else
if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
//Add to image list
final byte[] imageData = output.toByteArray();
Images.addImage(imageData);
If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.
-
Reading Contents of File and displaying output
I'm trying to read the contents of a file, then loop through the contents, perform some formatting, and display the output. Should I read the file into an array? What is the best approach? Thanks in advance.
Depends. Is it a text file? Can you format each line independent of others? If so, you can just read one line at a time (BufferedReader) and pass it to wherever the display is. If you need to work on the file as a whole, then you need read it all at once.
-
Read content of file which is ZIPed
I need to read contents of a file which is present in ZIP file.
The zip file is present on online server. I am able to get the Zip Input stream for the Zip file and also able to retrive the file names which are present but when I am trying to retrive the content of file is get a String which has only the file names of the zip. Please suggest what to do.
Following is my Code.
// aConn.getInputStream() Gives me access to Zip file present on online Server
ZipInputStream fileIn = new ZipInputStream(aConn.getInputStream());
anEntry = inputStream.getNextEntry();
if (anEntry != null) {
String filename = arEntry.getFilename();
byte[] b = new byte[2024];
fileIn.read(b);
sb.append(b.toString());
}Reading an input stream into an array of bytes and then calling toString() on that byte array isn't going to give you the contents of the input stream meaningfully. For one thing it might not even be textual data. And secondly that's not how you get textual data.
A better approach would probably be to get the number of bytes of the given entry from the ZipEntry.getSize method, create a byte array of that size, load only that many bytes, and then (if you're sure it's text data) send the byte array to a String constructor. Or you could use a java.io.ByteArrayOutputStream for that. Note that you'll need to know the character encoding for this. -
How to read contents of files that do not fall under public security group?
Hi,
I need to read the contents of a WCM based xml file that does not fall under public security.
The process is like this:
First the user makes chnages to the content.
The workflow will be triggred based on the security group metadata that is associated with the content.
Once the content is finally approved our workflow calls a custom idoc script.
First we tried directly reading the xml contents from the idoc script which was still in the context of workflow. But since content item is still in workflow I was not able to read the changes. So I created a separate content publisher thread and read the DOC_INFO and checked for the dStatus value. If the value is RELEASED then I reading contents by calling ssIncludeXml idoc script.
This was working fine for public content. But now the requirement is that all content cannot be public. Content authors should not be able to edit the content that does not belong to their group, So we created security groups (and roles) and are associating that groups to the relavent content.
Beacuse of this change I am not not able to read the non public content. The call to DOC_INFO_BY_NAME service, which gives all the content files' metadata, is expecting the user to be logged in to give the details.
I tried calling the CHECKIN service with sysadmin and captured the cookies returned by that service and use cookies for the DOC_INFO_BY_NAME service call. But the service call was faling. It is throing the 401 forbidden error with the message that user needs to be logged in to get the details.
How to address this problem. Someone please help.
Note: I also tried using ridc for this. I was able to get it working but since it is executing in the context of server ridc api is changing server's environment properties like HTTP_HOST, HTTP_CGIPATHROOT etc. It also seemed like system was becoming non functional after using ridc. When I called check-in the system metadata values like security group are no more loading. Not sure if ridc is the culprit here but worried that it might be causing this issue.
Regards,
PratapSorry, I posted too much details while posting this question. I was saying "not able to read *non* public content".
Anyway, I was able to resolve the issue. I was able to authenticate with sysadmin credentials in the request to service using basic authentication and was able to read doc info with that credential.
But I realized there is more than option for reading secure content.
- I could set user name as sysadmin in the m_environment (if I am in the context of a service) and the call the DOC_INFO_BY_NAME service.
- I can post an HTTP request to DOC_INFO_BY_NAME service with sysadmin credentials and do basic authorization via the connection. (This is what i have done successfully as of now )
- I could add guest role to all security groups with R (read) privileges.
I will look into all options and implement the one which is more apt.
Regards,
Pratap -
Open and read from text file into a text box for Windows Store
I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
Thanks
WendelThis is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using System.IO;
namespace TextFileDemo
public class TextFileHelper
async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
try
using (var s = await file.OpenStreamForWriteAsync())
s.Write(fileBytes, 0, fileBytes.Length);
return true;
catch
return false;
async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
string returnvalue = string.Empty;
try
var file = await local.OpenStreamForReadAsync(filename);
using (StreamReader streamReader = new StreamReader(file))
returnvalue = streamReader.ReadToEnd();
catch (Exception ex)
// do somthing when exception
return returnvalue;
async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
string returnvalue = string.Empty;
try
var file = await local.OpenStreamForReadAsync(filename);
using (StreamReader streamReader = new StreamReader(file))
returnvalue = streamReader.ReadToEnd();
catch (Exception ex)
// do somthing when exception
return returnvalue;
show how to use it as below
async private void Button_Click(object sender, RoutedEventArgs e)
string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
Debug.WriteLine(txt);
在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。 -
Reading a text File into a JTextArea
I know this is really basic question, but what is the best and/or simplest way to read text from a .txt file into a JTextArea? I'm new to Java and any help anyone can provide would be greatly appreciated.
it should be in quotes only if it is a string repersentation of a String class.
FileReader reader = new FileReader("readme.txt");
quotes are not needed if you write it this way
String filename = "readme.txt";
FileReader reader = new FileReader(filename);
...remember that String is a class and not a data type, it is also a special case in java where the class can act like a datatype in declarations.
I don't think anything else can behave like this in java
String text = "sometext";
"sometext".equals(text);
this returns true. -
How to read/write .CSV file into CLOB column in a table of Oracle 10g
I have a requirement which is nothing but a table has two column
create table emp_data (empid number, report clob)
Here REPORT column is CLOB data type which used to load the data from the .csv file.
The requirement here is
1) How to load data from .CSV file into CLOB column along with empid using DBMS_lob utility
2) How to read report columns which should return all the columns present in the .CSV file (dynamically because every csv file may have different number of columns) along with the primariy key empid).
eg: empid report_field1 report_field2
1 x y
Any help would be appreciated.If I understand you right, you want each row in your table to contain an emp_id and the complete text of a multi-record .csv file.
It's not clear how you relate emp_id to the appropriate file to be read. Is the emp_id stored in the csv file?
To read the file, you can use functions from [UTL_FILE|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm#BABGGEDF] (as long as the file is in a directory accessible to the Oracle server):
declare
lt_report_clob CLOB;
l_max_line_length integer := 1024; -- set as high as the longest line in your file
l_infile UTL_FILE.file_type;
l_buffer varchar2(1024);
l_emp_id report_table.emp_id%type := 123; -- not clear where emp_id comes from
l_filename varchar2(200) := 'my_file_name.csv'; -- get this from somewhere
begin
-- open the file; we assume an Oracle directory has already been created
l_infile := utl_file.fopen('CSV_DIRECTORY', l_filename, 'r', l_max_line_length);
-- initialise the empty clob
dbms_lob.createtemporary(lt_report_clob, TRUE, DBMS_LOB.session);
loop
begin
utl_file.get_line(l_infile, l_buffer);
dbms_lob.append(lt_report_clob, l_buffer);
exception
when no_data_found then
exit;
end;
end loop;
insert into report_table (emp_id, report)
values (l_emp_id, lt_report_clob);
-- free the temporary lob
dbms_lob.freetemporary(lt_report_clob);
-- close the file
UTL_FILE.fclose(l_infile);
end;This simple line-by-line approach is easy to understand, and gives you an opportunity (if you want) to take each line in the file and transform it (for example, you could transform it into a nested table, or into XML). However it can be rather slow if there are many records in the csv file - the lob_append operation is not particularly efficient. I was able to improve the efficiency by caching the lines in a VARCHAR2 up to a maximum cache size, and only then appending to the LOB - see [three posts on my blog|http://preferisco.blogspot.com/search/label/lob].
There is at least one other possibility:
- you could use [DBMS_LOB.loadclobfromfile|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#i998978]. I've not tried this before myself, but I think the procedure is described [here in the 9i docs|http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96591/adl12bfl.htm#879711]. This is likely to be faster than UTL_FILE (because it is all happening in the underlying DBMS_LOB package, possibly in a native way).
That's all for now. I haven't yet answered your question on how to report data back out of the CLOB. I would like to know how you associate employees with files; what happens if there is > 1 file per employee, etc.
HTH
Regards Nigel
Edited by: nthomas on Mar 2, 2009 11:22 AM - don't forget to fclose the file... -
Hi all,
I'm new to flex and have been asked to provide a small widget
that will display the contents of a csv in a list. Can I use the
HTTPService to open a csv file and then create an actionscript 3
function to parse it? If so can anyone point me to a tutorial on
how to parse a csv file please.
Thanks in advanceHello Sir,
I am new to flex and want to read a csv file and using below code but does not seems to be working. Can you please help?
i use below code but did not work
var file:File = evt.currentTarget as File;
file = file.resolvePath(file.nativePath);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var fileData:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
var endings:Array = [File.lineEnding, "\n", "\r"];
but for some reason it return "ÐÏ ࡱá" funny value. Any idea why don't i get the correct data from file.
belwo is the csv file i am trying to open.
Title
Given_Name
Surname
Gong
Salutation
Position
Organisation
Address_Line_1
Address_Line_2
Address_Line_3
Suburb
State
Postcode
Country
Home_Phone
Fax
Other_Phone
User_Field_1
User_Field_2
User_Field_3
User_Field_4
Mobile_Phone
Second_Address
Second_Address_Line_1
Second_Address_Line_2
Second_Address_Line_3
Second_Suburb
Second_State
Second_Country
Second_Postcode
Langcode
Website
Mr.
Jeff
Alexander
Retention Marketing
Monday, April 13th, 2009
Mr.
Anthony
Demaso
Retention Marketing
Monday, April 13th, 2009
Sally
Swinamer
Yield
Monday, April 13th, 2009
Chris
Torbay
Yield
Monday, April 13th, 2009
Annette
Warring
Genesis Vizeum
Monday, April 13th, 2009
Mr.
Mark
Khoury
Genesis Vizeum
Monday, April 13th, 2009
Mr.
Andy
Thorndyke
Thorsons
Monday, April 13th, 2009
Shannon
Rutherford
Central Reproductions
Monday, April 13th, 2009
Mr.
Rob
Greenwood
Central Reproductions
Monday, April 13th, 2009
Lisa
Marchese
Des Rosiers
Monday, April 13th, 2009
Mr.
Michael
Whitcombe
McMillan LLP
Monday, April 13th, 2009
Thanks,
Gill
Maybe you are looking for
-
Iphone 5s incoming call number displays incorrectly.
Whenever I call my wife's Iphone from work, the number displays incorrectly on her caller ID. It is always dropping the third number of the area code, so if my work number was 123-456-7890, then when I call her it shows up on her phone as 124-567-89
-
Move 10.5 Server HD from one G5 to another?
Wow, I can't believe I'm posting this, but let's pretend it's 2007 and roll with it. So, I have a legacy FileMaker Server (FileMaker Server v10) running on a dual 2.3Ghz Power Mac G5 with Leopard Server (10.5.8). Aside from FileMaker Server, the only
-
NodeManager not able to start second managed server in same machine
Hi, I am facing an issue, I am not able start a second ManagedServer(MG2) using nodemanager (through AdminConsole) My setup is as below: Server 1 1) Admin Server + ManagedServer (MG1) (INSTALL LOCATION: /opt/web/MyServer1) 2) Second Managed Server (M
-
Well, i just bought a hawking Ethernet bridge. i set it up according to the manuel, and now i plue it into the back of my mac and it computer doesn't work. i try and set it up manually, but it won't connect. anyone have any ideas?
-
Dear All, Where can I get the Slide show on SAP HR to give the Presentation to Client in USA - [Client has not implemented HR module of SAP]. Waiting for your reply. Thanks.