Reading into plist files
Hi,
I'm building an app that relies heavily on reading plist files. I've got the basics down using System Events, for example:
tell application "System Events"
set plistFile to "/Library/Preferences/com.domain.prefs.plist"
set returnVal to (value of property list item "MyValue" of property list file plistFile)
display dialog returnVal
end tell
To extract from the following plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>MyValue</key>
<string>1000</string>
</dict>
</plist>
But of course I need to read further into plist files, count the number of re-occurrences of certain items and so on. For example, if I wanted to read into the following plist file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>MyValue</key>
<key>ArrayInfo</key>
<array>
<dict>
<key>Bool</key>
<true/>
<key>Value1</key>
<string>1000</string>>
</dict>
<dict>
<key>Bool</key>
<true/>
<key>Value1</key>
<string>4000</string>>
</dict>
</array>
</dict>
</plist>
How can I extract, for example, the number of records within the array and then create an AS list of each re-occurrence of 'Value1' or 'bool'?
Any help on this or any links to good tutorials will be much appreciated.
Many thanks.
Satimage also has a XMLLib osax with terminology to handle property lists, for example:
set TheOpenPlist to PlistOpen (choose file)
repeat with x in items of (PlistGet TheOpenPlist key "ArrayInfo")
log x
end repeat
PlistClose TheOpenPlist
There is documentation and some examples here.
Similar Messages
-
Please Help: Automator to get text from Safari Reader into Text file
Hello All,
I was hoping that someone will be able to help me.
I would like for automator to obtain article text from a website without me having to manually cut and paste it.
I tried to put together a workflow to get text from webpage, but it unfortunatley get some information that I don't want for eg. Menu Bar Titles and additional links etc. What would be ideal is if I could only extract the data that shows when I use the Safari Reader function. I have tried a jave Readability Script, but this also extract the same information. Is there anyway someone could please kindly help me out with a nice Applescript or something?
If there is no way to do this, there could be another solution around this... if there was a way I could use automator to delete the first and last 10 lines of the text document.
Again, any help will be much appreciated.
Many thanks,
VicandMeliJvRHi David,
Thank you for your feedback. I would be happy to use a screen capture program, but Quicktime X seems to only allow me to record audio and record the video separately. I will do this as a last resort, but it's a big pain to try to line up the video audio.
Thank you! I will definitely do this if nothing else works. -
How to read Plist files?
I would like to know how to read a plist file. I have one that do not work properly and i received a message saying that there is a letter (c) that should not be there. Is is possible to take it off?
Plist files are just text files. You can open them with any text editor
http://en.wikipedia.org/wiki/Property_list -
I had been trying to read from a plist to get file names of data files and it works fine when i run it in safari but after making its widget and putting it into iBooks it doesnot works. Please tell me any new method to read p list or correct my function if there is any correction. my function is following.
function plistread(n)
if (window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.open("GET", "Spell_Check_3.plist", false);
xhttp.send();
xmlDoc = xhttp.responseXML;
var x = xmlDoc.getElementsByTagName("dict");
var imgnamex = x[n].getElementsByTagName("string")[0].childNodes[0].nodeValue;
xlength=x.length;
return imgnamex;See i need to access a plist file in my html5 widget, i implemented it in java script but it's not working so is there any other way to take out values from a plist file.
-
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);
在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。 -
Can no longer read plist files
I've got a script that iterates through a list of hostnames, connects to each host, looks for the existence of a list of applications, and if they exist reads their Info.plist for the version. This worked seamlessly until a couple of days ago. The only change I can think of is having changed my username on all of my Macs from <username> to <username>.sa to differentiate privileged accounts from unprivileged accounts. Yes, this caused a number of issues, and I've hunted them down. I can connect to every host with <username>.sa, perform actions with sudo, etc. What I can't do any more is read plist files, even when logged in locally:
quad:~ username.sa$ defaults read /Applications/Utilities/Adobe\ Flash\ Player\ Install\ Manager.app/Contents/Info.plist
2014-06-26 15:03:59.588 defaults[49157:507]
Domain /Applications/Utilities/Adobe Flash Player Install Manager.app/Contents/Info.plist does not exist
quad:~ username.sa$ ls -l /Applications/Utilities/Adobe\ Flash\ Player\ Install\ Manager.app/Contents/Info.plist
-rw-r--r-- 1 root wheel 1344 May 28 12:02 /Applications/Utilities/Adobe Flash Player Install Manager.app/Contents/Info.plist
quad:~ username.sa$ cat /Applications/Utilities/Adobe\ Flash\ Player\ Install\ Manager.app/Contents/Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>12E55</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>Adobe Flash Player Install Manager</string>
<key>CFBundleIconFile</key>
<string>FlashPlayerInstaller.icns</string>
<key>CFBundleIdentifier</key>
<string>com.adobe.flashplayer.installmanager</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Adobe Flash Player Install Manager</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>14.0.0.125</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>4H1503</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>10K549</string>
<key>DTSDKName</key>
<string>macosx10.6</string>
<key>DTXcode</key>
<string>0463</string>
<key>DTXcodeBuild</key>
<string>4H1503</string>
<key>NSMainNibFile</key>
<string>FPIMMain</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
The file is there. It is readable. I can read it... just not with the 'defaults' command. This is with all plists on all of my Macs.Please read this whole message before doing anything.
This procedure is a diagnostic test. It’s unlikely to solve your problem. Don’t be disappointed when you find that nothing has changed after you complete it.
The purpose of the test is to determine whether the problem is caused by third-party software that loads automatically at startup or login, by a peripheral device, by a font conflict, or by corruption of the file system or of certain system caches.
Disconnect all wired peripherals except those needed for the test, and remove all aftermarket expansion cards, if applicable. Start up in safe mode and log in to the account with the problem. You must hold down the shift key twice: once when you turn on the computer, and again when you log in.
Note: If FileVault is enabled, or if a firmware password is set, or if the startup volume is a Fusion Drive or a software RAID, you can’t do this. Ask for further instructions.
Safe mode is much slower to start up and run than normal, with limited graphics performance, and some things won’t work at all, including sound output and Wi-Fi on certain models. The next normal startup may also be somewhat slow.
The login screen appears even if you usually login automatically. You must know your login password in order to log in. If you’ve forgotten the password, you will need to reset it before you begin.
Test while in safe mode. Same problem?
After testing, restart as usual (not in safe mode) and verify that you still have the problem. Post the results of the test. -
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.
-
Problem in reading no. of files and writing into a single file
Hi,
Iam with Problem in reading no. of files and writing into a single file....
Iam reading no. of files stored in local directory.......
Iam able to read and print the data in files successfully....but while writing..only first file is being written...and the next files are not written in my output file...
plz tell me my mistake....I hope Iam doing some mistake while writing into file...PLz help.....
Basically my code structure is like this....
import java.io.*;
import java.util.regex.*;
import java.util.*;
import java.text.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
class Writing {
public static void main(String args[]) throws Exception {
FileOutputStream fileOut = new FileOutputStream("ServerResult.xls"); //my output file
int counter = 1;
File dir = new File("C:/Perform/ServerLogs");
String[] children = dir.list();
if( children == null)
System.out.println("The Directory mentioned does not exist");
else {
for (int fileNo = 0; fileNo < children.length; fileNo++ ) { //Files iteration starts
String filename = children[fileNo];
File logFile = new File(filename);
FileReader logFileReader = new FileReader(logFile);
BufferedReader logReader = new BufferedReader(logFileReader);
StringBuffer sBuf = new StringBuffer(5000);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow rowTitle;
HSSFRow rowReq;
HSSFRow rowRes;
String aLine = null;
boolean skip = false;
boolean readed = false;
boolean initReq = false;
boolean flag = false;
long requestTime = 0;
long responseTime = 0;
long recdTime = 0;
long sentTime = 0;
long hasTime = 0;
long presentTime = 0;
int hasCalls = 0;
Pattern startMessage = Pattern.compile("^<MESSAGE.*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern requestMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<ActName>(.*)</ActName>.*", Pattern.DOTALL);
Pattern requestMessage1 = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<Svc id=\"(.*)\">.*", Pattern.DOTALL);
Pattern responseMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern initMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"HostConnInit\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern initResMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*", Pattern.DOTALL);
Pattern initResIDMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*<IATA>"+args[0]+"</IATA>.*", Pattern.DOTALL);
Pattern sentMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgSentInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern rcvdMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgRcvdInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
DecimalFormat dcf = new DecimalFormat("########.##");
String actName = "";
if (fileNo ==0)
rowTitle = sheet.createRow((short)0);
rowTitle.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)0).setCellValue("Req/Res");
rowTitle.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)1).setCellValue("Action");
rowTitle.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)2).setCellValue("Server Time(in ms)");
rowTitle.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)3).setCellValue("Request Vs Response Time in Server(in ms)");
rowTitle.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)4).setCellValue("Time Taken By HAS/HOST(in ms)");
rowTitle.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)5).setCellValue("No. of HAS calls");
rowTitle.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)6).setCellValue("Data Size");
//wb.write(fileOut);
while((aLine=logReader.readLine()) != null) {
if(aLine.startsWith("<MESSAGE TYPE=\"EVENT\"")) {
Matcher m = startMessage.matcher(aLine);
if(m.find()) {
sBuf.setLength(0);
sBuf.append(aLine);
skip = false;
initReq = false;
m = initMessage.matcher(aLine);
if(m.find()) {
initReq = true;
} else {
if(initReq) {
m = initResMessage.matcher(aLine);
if(m.find()) {
sBuf.setLength(0);
sBuf.append(aLine);
skip = false;
} else if(aLine.startsWith("</MESSAGE>")) {
if(!skip) {
sBuf.append(aLine);
readed = true;
} else if(!skip){
sBuf.append(aLine);
if(!skip && readed) {
String tempStr = sBuf.toString();
if(tempStr.length() > 0) {
boolean reqMatched = false;
Matcher m = null;
if(initReq) {
m = initMessage.matcher(tempStr);
actName = "Intialization";
} else {
m = requestMessage.matcher(tempStr);
String time = "";
if(m.find()) {
reqMatched = true;
for (int i=1; i<=m.groupCount(); i++) {
String groupStr = m.group(i);
if(i == 1) {
time = groupStr;
} else if(i == 2) {
actName = groupStr;
} else if(!initReq){
m = requestMessage1.matcher(tempStr);
if(m.find()) {
reqMatched = true;
for (int i=1; i<=m.groupCount(); i++) {
String groupStr = m.group(i);
if(i == 1) {
time = groupStr;
} else if(i == 2) {
actName = groupStr;
if(time.length() > 0 ) {
try{
requestTime = sdf.parse(time).getTime();
}catch(Exception ex){}
System.out.println("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
//bw.write("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
String reqDataSize = dcf.format(((double)time.length()/1024.0))+"K" ;
rowReq = sheet.createRow((short)counter);
rowReq.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)0).setCellValue("Request");
rowReq.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)1).setCellValue(actName);
rowReq.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)2).setCellValue(time);
rowReq.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)3).setCellValue("");
rowReq.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)4).setCellValue("");
rowReq.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)5).setCellValue("");
rowReq.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)6).setCellValue(reqDataSize);
counter = counter +1;
System.out.println("counter is "+counter);
Matcher l = sentMessage.matcher(tempStr);
Matcher k = rcvdMessage.matcher(tempStr);
if(l.find()) {
for (int i=1; i<=l.groupCount(); i++) {
String groupStr2 = l.group(i);
try{
sentTime = sdf.parse(groupStr2).getTime();
}catch(Exception ex){}
if(k.find())
for(int j=1;j<=k.groupCount(); j++) {
String groupStr1 = k.group(j);
try{
recdTime = sdf.parse(groupStr1).getTime();
}catch(Exception ex){}
presentTime = (recdTime - sentTime);
hasTime = hasTime + presentTime;
hasCalls = hasCalls +1;
if(!reqMatched) {
if(initReq) {
m=initResIDMessage.matcher(tempStr);
} else {
m=responseMessage.matcher(tempStr);
if(m.find()) {
for (int i=1; i<=m.groupCount(); i++) {
String groupStr = m.group(i);
try{
responseTime = sdf.parse(groupStr).getTime();
}catch(Exception ex){}
String resDataSize = dcf.format(((double)tempStr.length()/1024.0))+"K" ;
rowRes = sheet.createRow((short)(counter));
rowRes.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)0).setCellValue("Response");
rowRes.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)1).setCellValue(actName);
rowRes.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)2).setCellValue(groupStr);
rowRes.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
rowRes.createCell((short)3).setCellValue((responseTime - requestTime));
rowRes.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
rowRes.createCell((short)4).setCellValue(hasTime);
rowRes.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
rowRes.createCell((short)5).setCellValue(hasCalls);
rowRes.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)6).setCellValue(resDataSize);
hasTime = 0;
hasCalls = 0;
counter = counter + 1 ;
sBuf.setLength(0);
readed = false;
wb.write(fileOut);
} // End of for (int fileNo = 0; fileNo < children.length; fileNo++ )
} //End of else
fileOut.close();
} //End of public static void main
} // End of ClassFirst of all, use [code]-tags to make your code readable, please.
I didn't do a complete inspection of your code (because it's too much and unreadable as it is) and I don't know POI, but creating a new HSSFWorkbook for each input file sounds fishy to me ... try re-using the workbook and just creating a new sheet in each iteration. -
How can one read a Excel File and Upload into Table using Pl/SQL Code.
How can one read a Excel File and Upload into Table using Pl/SQL Code.
1. Excel File is on My PC.
2. And I want to write a Stored Procedure or Package to do that.
3. DataBase is on Other Server. Client-Server Environment.
4. I am Using Toad or PlSql developer tool.If you would like to create a package/procedure in order to solve this problem consider using the UTL_FILE in built package, here are a few steps to get you going:
1. Get your DBA to create directory object in oracle using the following command:
create directory TEST_DIR as ‘directory_path’;
Note: This directory is on the server.
2. Grant read,write on directory directory_object_name to username;
You can find out the directory_object_name value from dba_directories view if you are using the system user account.
3. Logon as the user as mentioned above.
Sample code read plain text file code, you can modify this code to suit your need (i.e. read a csv file)
function getData(p_filename in varchar2,
p_filepath in varchar2
) RETURN VARCHAR2 is
input_file utl_file.file_type;
--declare a buffer to read text data
input_buffer varchar2(4000);
begin
--using the UTL_FILE in built package
input_file := utl_file.fopen(p_filepath, p_filename, 'R');
utl_file.get_line(input_file, input_buffer);
--debug
--dbms_output.put_line(input_buffer);
utl_file.fclose(input_file);
--return data
return input_buffer;
end;
Hope this helps. -
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. -
Read a csv file, fill a dynamic table and insert into a standard table
Hi everybody,
I have a problem here and I need your help:
I have to read a csv file and insert the data of it into a standard table.
1 - On the parameter scrreen I have to indicate the standard table and the csv file.
2 - I need to create a dynamic table. The same type of the one I choose at parameter screen.
3 - Then I need to read the csv and put the data into this dynamic table.
4 - Later I need to insert the data from the dynamic table into the standard table (the one on the parameter screen).
How do I do this job? Do you have an example? Thanks.Here is an example table which shows how to upload a csv file from the frontend to a dynamic internal table. You can of course modify this to update your database table.
report zrich_0002.
type-pools: slis.
field-symbols: <dyn_table> type standard table,
<dyn_wa>,
<dyn_field>.
data: it_fldcat type lvc_t_fcat,
wa_it_fldcat type lvc_s_fcat.
type-pools : abap.
data: new_table type ref to data,
new_line type ref to data.
data: xcel type table of alsmex_tabline with header line.
selection-screen begin of block b1 with frame title text .
parameters: p_file type rlgrap-filename default 'c:Test.csv'.
parameters: p_flds type i.
selection-screen end of block b1.
start-of-selection.
* Add X number of fields to the dynamic itab cataelog
do p_flds times.
clear wa_it_fldcat.
wa_it_fldcat-fieldname = sy-index.
wa_it_fldcat-datatype = 'C'.
wa_it_fldcat-inttype = 'C'.
wa_it_fldcat-intlen = 10.
append wa_it_fldcat to it_fldcat .
enddo.
* Create dynamic internal table and assign to FS
call method cl_alv_table_create=>create_dynamic_table
exporting
it_fieldcatalog = it_fldcat
importing
ep_table = new_table.
assign new_table->* to <dyn_table>.
* Create dynamic work area and assign to FS
create data new_line like line of <dyn_table>.
assign new_line->* to <dyn_wa>.
* Upload the excel
call function 'ALSM_EXCEL_TO_INTERNAL_TABLE'
exporting
filename = p_file
i_begin_col = '1'
i_begin_row = '1'
i_end_col = '200'
i_end_row = '5000'
tables
intern = xcel
exceptions
inconsistent_parameters = 1
upload_ole = 2
others = 3.
* Reformt to dynamic internal table
loop at xcel.
assign component xcel-col of structure <dyn_wa> to <dyn_field>.
if sy-subrc = 0.
<dyn_field> = xcel-value.
endif.
at end of row.
append <dyn_wa> to <dyn_table>.
clear <dyn_wa>.
endat.
endloop.
* Write out data from table.
loop at <dyn_table> into <dyn_wa>.
do.
assign component sy-index of structure <dyn_wa> to <dyn_field>.
if sy-subrc <> 0.
exit.
endif.
if sy-index = 1.
write:/ <dyn_field>.
else.
write: <dyn_field>.
endif.
enddo.
endloop.
REgards,
RIch Heilman -
Unable to read E$ table records into excel file in linux machine
Hi
I am using below code in ODI procedure to read E$ table record and store it in excel file
ODI Procedure: Technology=Java Beanshall and Command on Target I written below code and placed it in CKM Oracle KM
<@
String OS = System.getProperty("os.name").toLowerCase();
String v_path="";
if((OS.indexOf("win") >= 0))
v_path="D:\Unload_Dir\<%=snpRef.getSession("SESS_NO")%>.xlsx";
else if (OS.indexOf("mac") >= 0)
v_path="path details";
else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 )
v_path="/odi_a/oracle/Middleware/logs/wcds/odi_logs/<%=snpRef.getSession("SESS_NO")%>.xlsx";
else if (OS.indexOf("sunos") >= 0)
v_path="soliaris path";
@>
OdiSqlUnload "-FILE=<@=v_path@>" "-DRIVER=<%=odiRef.getInfo("DEST_JAVA_DRIVER")%>" "-URL=<%=odiRef.getInfo("DEST_JAVA_URL")%>" "-USER=<%=odiRef.getInfo("DEST_USER_NAME")%>" "-PASS=<%=odiRef.getInfo("DEST_ENCODED_PASS")%>" "-FILE_FORMAT=VARIABLE" "-ROW_SEP=\r\n" "-DATE_FORMAT=yyyy/MM/dd HH:mm:ss" "-CHARSET_ENCODING=ISO8859_1" "-XML_CHARSET_ENCODING=ISO-8859-1"
select * from <%=odiRef.getTable("L","ERR_NAME", "W")%>
But is not reading the data into .xlsx file ,
Please help me it is very urgent
Can I use below code
String os = "";
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
os = "windows";
} else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
os = "linux";
} else if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
os = "mac";
T
his is high priority, please help me urgent
Regards,
Phanikanth
Edited by: Phanikanth on Feb 28, 2013 5:43 AM
Edited by: Phanikanth on Feb 28, 2013 6:00 AM
Edited by: Phanikanth on Feb 28, 2013 7:42 AMHi,
can you describe what is happening when you run the ODI procedure described below:
- Does the procedure fail with an error, if yes, which error(full details)?
- Does the procedure pass but no xslx file is been created?
- Does the procedure pass and an xslx file is been created, but Excel can't read it? If yes, what is the structure of the xslx file when read in an editor?
What I can see from your code below is that you have choosen -FILE_FORMAT=VARIABLE, but the XSLX format is supposed to be XML.
Regards,
Alex -
Reading entire txt file into memory?
When you are using BufferedReader to read info into a buffer, that means you are reading the file into memory, correct? (Is that what buffer means?)
I want to look for pattern matches in text files (about 1000 of them) using the regex utils. But I don't want to read and examine the text files line by line. I want to read in the entire text file into memory first and then look for the pattern matches. The text files generally don't exceed about 15K in size. I'm only going one file at a time, too, so this won't give me any out of memory errors, will it?
And more importantly, how do I do it? I mean the "reading in the file" part only. I have my RegEx, I have my array of files to examine already. I just can't figure out the right code to use to read each file into memory before I look for pattern matches.
Could someone help, please?When you are using BufferedReader to read info into a
buffer, that means you are reading the file into
memory, correct? (Is that what buffer means?)Yes.
I want to look for pattern matches in text files
(about 1000 of them) using the regex utils. But I
don't want to read and examine the text files line by
line.Why not?
I want to read in the entire text file into
memory first and then look for the pattern matches.Why?
The text files generally don't exceed about 15K in
size. I'm only going one file at a time, too, so
this won't give me any out of memory errors, will
it?Depends on how much memory you've given the VM and how much of that it's using already at the time you read the files, but in general, probably not a problem.
And more importantly, how do I do it? I mean the
"reading in the file" part only.Use BufferedReader to read line by line and then append each line (plus a newline, since BR.readLine() strips those off) to a StringBuilder.
Or use a BufferedInputStream and and array that's as big as the file, and in a loop, try to read as much as is left into that array at an offset equal to how much has been read so far.
I still think this is probably not a good approach though. -
Hi Gang,
In my application, I want to create files Using the Analog Waveform Editor and then, through LavVIEW, play them out through an D/A.
I've not been able to read the .hws file into LV. I've tried two methods:
Using the Read Waveform VI in the Waveform palette, yields Error -1821.
I looked in the knowledgebase and found the article "Using the Analog Waveform Editor and HWS Files with Multifunction DAQ Devices" That recommended using the HWS VIs that are a part of the FGEN driver. I tried that and get an Error -21515.
The file I want to read is quite small, only 20 samples. Is there some limitation on .hws files or the Waveform Editor I'm not aware of?
I've attached the file if anyone is willing to experiment. I had to change the extension from .hws to .txt to be able to attach it.
All responses will be appreciated.
Thanks,
Roger
Solved!
Go to Solution.
Attachments:
Havesine.TXT 108 KBInteresting. I tried to look at your file with the low level read .hws file vi's and I too got error -21515. So I tried the NI-HWS express load.vi and it looks like it worked. I'm not familiar with the analog waveform editor...does it store using the dynamic data type? Oh I converted the dynamic data to 1d array of waveforms using the convert from dynamic data.vi.
Using LabVIEW 2010SP1 and TestStand 4.5 -
Read info about files in specific folder into internal table
Hi Experts
I need to have last modified date and filename information read into an internal table. I need to read in the information of all files in a specific (UNIX) folder (I do not know the name of the single files).
I really hope someone can help.
Thanks a lot
Kind regards,
TorbenHi Guys
Thanks a lot for you input.
I managed to get my program to works as follows:
REPORT ZDELETE_ARCHIVING_FILES.
*Step 1: Get the list of files in the directory into internal table :
DATA: DLIST LIKE EPSFILI OCCURS 0 WITH HEADER LINE,
DPATH LIKE EPSF-EPSDIRNAM,
MDATE LIKE SY-DATUM,
MTIME LIKE SY-UZEIT.
DATA: BEGIN OF FATTR OCCURS 0,
FILE_NAME LIKE EPSF-EPSFILNAM,
FILE_SIZE LIKE EPSF-EPSFILSIZ,
FILE_OWNER LIKE EPSF-EPSFILOWN,
FILE_MODE LIKE EPSF-EPSFILMOD,
FILE_TYPE LIKE EPSF-EPSFILTYP,
FILE_MTIME(12),
END OF FATTR.
DATA: P_PATH(50) TYPE C.
CONCATENATE '/ARCHIVE/' sy-sysid '/archive' INTO P_PATH.
* WRITE: / P_PATH.
DPATH = P_PATH.
*Get files in folder - read into internal table DLIST
*if filenames are longer than 40 characters
*then use FM SUBST_GET_FILE_LIST.
CALL FUNCTION 'EPS_GET_DIRECTORY_LISTING'
EXPORTING
DIR_NAME = DPATH
TABLES
DIR_LIST = DLIST
EXCEPTIONS
INVALID_EPS_SUBDIR = 1
SAPGPARAM_FAILED = 2
BUILD_DIRECTORY_FAILED = 3
NO_AUTHORIZATION = 4
READ_DIRECTORY_FAILED = 5
TOO_MANY_READ_ERRORS = 6
EMPTY_DIRECTORY_LIST = 7
OTHERS = 8.
IF SY-SUBRC EQ 0.
*Step 2: Read the file attributes into an internal table
*Read info about the files (attributes) into the internal table FATTR
*as we need info about the last time it was changed (MTIME)
LOOP AT DLIST.
CALL FUNCTION 'EPS_GET_FILE_ATTRIBUTES'
EXPORTING
FILE_NAME = DLIST-NAME
DIR_NAME = DPATH
IMPORTING
FILE_SIZE = FATTR-FILE_SIZE
FILE_OWNER = FATTR-FILE_OWNER
FILE_MODE = FATTR-FILE_MODE
FILE_TYPE = FATTR-FILE_TYPE
FILE_MTIME = FATTR-FILE_MTIME
EXCEPTIONS
READ_DIRECTORY_FAILED = 1
READ_ATTRIBUTES_FAILED = 2
OTHERS = 3.
IF SY-SUBRC EQ 0.
FATTR-FILE_NAME = DLIST-NAME.
APPEND FATTR.
ENDIF.
ENDLOOP.
SORT FATTR BY FILE_NAME.
DATA: time(10), date LIKE sy-datum.
DATA: months TYPE i.
DATA: e_file TYPE string.
LOOP AT FATTR.
CLEAR: time, months, e_file.
IF FATTR-FILE_NAME(10) = 'archive_BW'.
*Convert the unix time into readable time
PERFORM p6_to_date_time_tz(rstr0400) USING FATTR-FILE_MTIME
time
date.
*Calculate the number of months between date (MTIME) and current day
*ex 31.03.2009 - 01.04.2009 = 1 month
*ex 01.02.2009 - 01.04.2009 = 2 month
CALL FUNCTION 'MONTHS_BETWEEN_TWO_DATES'
EXPORTING
i_datum_von = date
i_datum_bis = sy-datum
IMPORTING
e_monate = months.
CONCATENATE DPATH '/' FATTR-FILE_NAME INTO e_file.
* WRITE: / FATTR-FILE_NAME,
* FATTR-FILE_SIZE,
* date,
* time,
* sy-datum,
* months,
* e_file.
*Step 3: Delete files where months > 1
IF months > 1.
OPEN dataset e_file for output in text mode encoding default.
DELETE dataset e_file.
CLOSE dataset e_file.
ENDIF. "months > 1
ENDIF.
ENDLOOP.
ENDIF.
Maybe you are looking for
-
Can you save editable pdf as read only
I have a client who's using an editable pdf that I set up in the full version of Acrobat 8.0. They would like to edit the doc in Acrobat Reader and then do a save as and make the doc "read Only" so that their viewers can't edit the document after the
-
Connecting via ethernet?
I am in a hurry to connect my IBook G4 to my wife's G3 desktop in order to allow her to take my IBook to the States from the UK for a prolonged stay. What's the best way to transfer all my data including in Applications ( incl Word)
-
SAPscript with request correspondence ....
Hi all, In standard SAP, step to step I do: 1. T_code FB12 <- create Request Correspondence 2. T_code F.61 <- Trigger for corespondence with Correspondence = 'SAP04'. 3. T_code SP01 <- Output control / Choose spool req. number and show SAPscript for
-
When I place an Aperture photo on the cloud to share with friends, the idenfifcation information I have entered for the photo does not transfer to the cloud and thus my friends get only the photo. Is there a setting I am missing that would allow the
-
I've been trying to convert some old CS files into CS5 files. These are simple files: some text, simple line work, a photo or two (tiff, jpeg or eps) and some simple illustrator art. These files were typically 500k to 800k. The updated files are 3 -