Text File is like this
my text File is like this:
CUS0000001,Manish Paliwal,9818689349,25
CUS0000002,Manish Paliwal,9818689349,25
CUS0000013 Manish Paliwal 9818689349 25
CUS0000014 Manish Paliwal 9818689349 25
CUS0000015;Manish Paliwal;9818689349;25
CUS0000016;Manish Paliwal;9818689349;25
In above file some records are seprated by ",","TAB" or ";". They can be any special characters.
I want to extract all records and insert into Customer table which have Cust_ID, Cust_Name, Cust_Phone & Cust_Age.
If file have single seprator pattern records then it is possible. But when a file have more than one type seprator formates then i have no idea.
So please tell me in detail, If is it possible?
It's easy... first read the manuel.
Here are some clues:
1) Duplicate the KM you want to update...
2) Rename this KM
3) Create a new step
4) Choose the right technology in our case: JYTHON.
5) Write the script... For exemple:
import os
srcFile = "<%=odiRef.getSrcTablesList("", "[SCHEMA]/[RES_NAME]", "", "")%>"
tmpFile = "<%=odiRef.getSrcTablesList("", "[SCHEMA]/tmp_[RES_NAME]", "", "")%>"
fieldSep = "<%=odiRef.getSrcTablesList("", "[FILE_SEP_FIELD]", "", "")%>"
os.rename(srcFile , tmpFile )
fsrc = open(tmpFile, 'r')
ftrg = open(srcFile, 'w')
for lsrc in fsrc.readlines():
for i in Separateur:
lsrc=lsrc.replace(i,fieldSep)
ftrg.write(lsrc)
fsrc.close()
ftrg.close()
that's all
Similar Messages
-
I have a question about extracting pages. When I do the function, adobe saves the individual files as "<file name><space><page number>", so the files look like this "filename 1.pdf", "filename 2.pdf", "filename 3.pdf". Without too many gory details, I am using excel to concatenate some data to dynamically build a hyperlink to these extraced files. It casues me problems, however, for the space to be the the file name. Is there any way to change the default behavoir of this function to perhaps use a dash or underscore instead of a space?
No, you can't change the default naming scheme. You can do it yourself if you extract the pages using a script instead of using the built-in command.
-
Why are files opening like this?
(I can't put it into words so)
files on open look like this:
instead of this:
it's driving me nuts, ruining my work flow
thanks!
psCC retina mbp 10.9ok, it was the dual monitor set-up. different resolutions. the dell ultrasharp must stay @ 1920 x 1000 and the mbp must stay @ 1680 x 1050 (even if it doesn't want to). thanks for looking. it made me find the solution.
-
Reading characters from a text file into a multidimensional array?
I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
This didn't paste evenly, but thats not a big deal. Just giving an idea.
19
5..................
And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.
Code:
//Scanner to read file
Scanner input = null;
try{
input = new Scanner(fileName);
}catch(RuntimeException e) {
System.err.println("Couldn't find the file");
System.exit(0);
//Set the size of the maze
while(input.hasNextInt())
size = input.nextInt();
//Set Limits on coordinates
Coordinates.setLimits(size);
//Set the maze[][] array equal to this size
maze = new char[size][size];
//Fill the Array with maze values
for(int i = 0; i < maze.length; i++)
for(int x = 0; x < maze.length; x++)
if(input.hasNextLine())
String insert = input.nextLine();
maze[i][x] = insert.charAt(x);
Any advice would be loved =DCode-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
for(int x = 0; x < maze.length; x++) {
if (input.hasNextLine()) {
String insert = input.nextLine();
maze[x] = insert.charAt(x);
}Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
if (input.hasNextLine()) {
String insert = input.nextLine();
for(int x = 0; x < insert.size(); x++) {
maze[i][x] = insert.charAt(x);
}Otherwise, only one character per line is read and storing a character actually should fail. -
Importing text file (with file names) into Automator.. is it possible?
Hello all,
I have been working with Windows Batch files for my line of work. I have a couple of file names in a text file (a column), which I want to copy from one folder of one hdd to another folder on a different hdd. I have been trying to do this kind of work with a Mac. I already know how you copy and rename files in automator (which isn't difficult, of course) but you have to 'select' the files in the finder first (with get specified items).
But the only way i see that you can specify items is by selecting them... is there a way to import a text file with all the file names instead of selecting all the file names manually?
or is there an AppleScript alternative which I can use to import the text file (or just copy into applescript) and run before the query's of copying and renaming the files? I am kind of new to Apple programming.
The text file looks like this:
image1.jpg
image2.jpg
etc..
so there has to be a command to: 'goto' a specific folder as well.
Thanks in advance!You can import text files, but if they are just names you will need an additional action to add the source folder path. A *Run AppleScript* action can be used, for example:
Tested workflow:
1) *Ask for Finder Items* {Type: files } -- choose the text file containing the names
2) *Combine Text Files* -- this gets the text file contents
3) *Filter Paragraphs* { return paragraphs that are not empty } -- skip blank lines
4) *Run AppleScript* -- copy and paste the following script:
<pre style="
font-family: Monaco, 'Courier New', Courier, monospace;
font-size: 10px;
font-weight: normal;
margin: 0px;
padding: 5px;
border: 1px solid #000000;
width: 680; height: 340px;
color: #000000;
background-color: #FFEE80;
overflow: auto;"
title="this text can be pasted into an Automator 'Run AppleScript' action">
on run {input, parameters} -- add folder path
add the specified folder path to a list of file names
input: a list of text items (the file names)
output: a list of file paths (aliases)
set output to {}
set SkippedItems to {} -- this will be a list of skipped items (errors)
set SourceFolder to (choose folder with prompt "Choose the folder containing the file names") as text -- this is the folder containing the names
repeat with AnItem in the input -- step through each name in the input
try
set AnItem to SourceFolder & AnItem -- add the prefix
set the end of the output to (AnItem as alias) -- test
on error number ErrorNumber -- oops
set ErrorNumber to (" (" & ErrorNumber as text) & ")" -- add the specific error number
set the end of SkippedItems to (AnItem as text) & ErrorNumber
end try
end repeat
ShowSkippedAlert for SkippedItems
return the output -- pass the result(s) to the next action
end run
to ShowSkippedAlert for SkippedItems
show an alert dialog for any items skipped, with the option to cancel the workflow
parameters - SkippedItems [list]: the items skipped
returns nothing
if SkippedItems is not {} then
set {AlertText, TheCount} to {"Error with AppleScript action", count SkippedItems}
if TheCount is greater than 1 then
set theMessage to (TheCount as text) & space & " items were skipped:"
else
set theMessage to "1 " & " item was skipped:"
end if
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set {SkippedItems, AppleScript's text item delimiters} to {SkippedItems as text, TempTID}
if button returned of (display alert AlertText message (theMessage & return & SkippedItems) ¬
alternate button "Cancel" default button "OK") is "Cancel" then error number -128
end if
return
end ShowSkippedAlert
</pre>
5) *Copy Finder Items* { To: _your external drive_ } -
Read a text file and display a xy graph
Hi!
I am using LabVIEW 8.5, and I am trying to read columns from
a file and plot with xy graph. I can do it with two channels, but I am having
problems when the numbers of channels connected increase (maybe six or ten).
My text file looks like this:
[Where first column x = time, the rest of the columns are
channels = y]
8.828 22.604 23.076 [The number of channels connected can
change]
9.828 22.604 22.604
10.828 21.658 22.131
11.828 22.131 22.131
12.828 22.131 22.131
13.828 22.604 22.604
14.828 21.658 22.604
15.828 22.131 22.131
16.828 21.658 23.076
17.828 22.604 22.131
18.828 22.131 22.604
I attached a picture of what I already try… Now I am trying
a combination of those. If anyone has some
advice or suggestion, please let me know.
Sincerely,
Julieta.
Solved!
Go to Solution.
Attachments:
xygraph.PNG 25 KBThanks for the advice!... I just modified what I had a
little bit and it is working, maybe is not the optimums solution…
I would like to make the time invisible in the graph… It that possible? I attached a picture of my graph, because my English is not good. There are two lines near to 22 (two channels
connected at that moment), and a line near to 0 which is time (the strong pink one). I would like to make invisible the strong
prink one only. I try to make invisible,
but I fail… I changed colors looking for another solution and I fail again,
because it is taking the colors that I choose for the channels. I can not disable because I need it to make
the x axes works with the time that I already saved.
If someone has an advice or suggestion I really appreciate it…
Sincerely,
Julieta.
Attachments:
xygraph.PNG 9 KB -
How to find the ocuurence of a word from LIST A in LIST B in a text file?
Hey if you look at the text file there is LIST A and LIST B.. i need to find the ocuurence of a word from LIST A in LIST B. Eg: if my output is (1,3)
then first word from LIST A occurs in 3 places in LIST B.
Can you please get the sample code to do this process.
Please let me know..
My text file looks like this below :
phrases.txt
LIST A
aamsz
abaffiliate
aboard casino
above computer
above pop
above violat
LIST B
http://209.153.231.131
HTTP/1.0 200 OK
Server: Microsoft-IIS/5.0
Date: Mon, 02 Feb 2004 11:53:26 GMT
IISExport: This web site was exported using IIS Export v2.2
IISExport: This web site was exported using IIS Export v2.2
Content-Length: 274
Content-Type: text/html
Set-Cookie: ASPSESSIONIDSSDBBBAR=OOGFKOJBMKMDCGPIHPADALHB; path=/
aboard casino
Cache-control: private
abaffiliate
above computerThe key difference is that Vector is synchronized whilst ArrayList is not. Synchronized means that the classes methods can safely be accessed by different threads and as your application will not be multithreaded then the ArrayList is possibly the better option.
To store Strings in an ArrayList, you first need to declare the ArrayList object something like this;
ArrayList<String> listAList = new ArrayList<String>();and you would obviously do something similar for the ArrayList that will hold the Strings that should belong to List B.
The first thing to note is that you can use the new (well new in version 1.5 anyway) generics techniques to specify the type of the object the ArrayList will hold; Strings in this case.
To add a value into the ArrayList once you have read it from the file and decided if it belongs in the List A or List B ArrayList, all you need to do is call the add() method of the ArrayList something like this;
// Assume that you read the line from the file into a variable called temp;
listAList.add(temp);To compare the two lists, the easiest option would be to iterate through one ArrayList and ceheck to see if the values you recover from it are duplicated in the other ArrayList. Luckilly, ArrayList has another method that helps here, it is called contains();
Assuming that you have two ArrayList(s), one called listAList that holds the Strings that belong to List A and another called listBList that holds the Strings that belong to ListB, you could do something like this to check for duplicates;
for(String element : listAList) {
if(listBList.contains(element)) {
System.out.println("Found a match");
}Hope that helps. -
How to format the spaces in a text file using bat file scripting
Currently the records in my text file are like this:
100239 0000015.00
QRP
I want them to be like this:
100266 0000015.00 QRP
There should be 6 spaces before the first column and 8 spaces after that. There should be 1 space between the second and third columns.
Generally this file contains approx 1000 records.
Any help is highly appreciated.
Thank you.So far it's like this:
for /f "skip=2 delims=*" %%a in (C:\Bonus_File_Export.txt) do (
echo %%a >>C:\newfile.txt
xcopy C:\newfile.txt C:\Bonus_File_Export.txt /y
del C:\newfile.txt /f /q
I've to format a text file generated by the tool Microstrategy and it feed it to another system in a specific format. Ihave removed the headers with the above script but was unable to remove the spaces between those columns.
You can use this code as a basis for your script:
@echo off
set Line=
if exist d:\temp\newfile.txt del d:\temp\newfile.txt
for /F "skip=2 tokens=1-2" %%a in (d:\temp\test.txt) do call :Sub %%a %%b
goto :eof
:Sub
if not "%2"=="" (
set Line= %1 %2
) else (
echo %Line% %1>>d:\temp\newfile.txt
It works provided that your input file uses this format:
Header line
Header line
100239 0000015.00
QRP
100240 0000016.00
QRR
100241 0000017.00
QRS
100242 0000018.00
QRT
100243 0000019.00
QRU
100244 0000020.00
QRV -
I am trying to read in questions, possible answers and the correct answer from a text file.
The text file looks like this
1. what is blah blah blah?
a. something
b. something else
c. none of the above
b
where the last line of the file is a character which is the correct answer.
I can read all these in as a string but I have to read the last line in as a character .
can you please help.I'm not sure if this is what you need but, take a look:
import java.io.*;
public class questions
public static void main(String[] args)
try
Question a=new Question();
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File("answers.txt")));
out.writeObject(a);
ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File("answers.txt")));
Question b=(Question)in.readObject();
char answer=b.getAnswer();
System.out.println(answer);
catch(IOException e)
System.out.println(e);
catch(ClassNotFoundException e)
System.out.println(e);
class Question implements Serializable
String q;
String a1;
String a2;
String a3;
char c;
public Question()
q=new String("The Question");
a1=new String("1st possible choise");
a2=new String("2st possible choise");
a3=new String("3st possible choise");
c='c';
public void setQuestion(String que)
q=que;
public void setAnswer1(String an1)
a1=an1;
public void setAnswer2(String an2)
a2=an2;
public void setAnswer3(String an3)
a3=an3;
public void setAnswer(char an)
c=an;
public char getAnswer()
return c;
Ofcource all methods in Question class should be adapted to the needs of your program.
If i helped help me too.. (duke $) -
Reading through a text file and then sorting
I'm having a lot of problems with this.
I have to read through a text file and I have to split the string up so that it is seperated into individual tokens. A line from the text file looks like this. addEvent(new Bell(tm + 9000)). I have to grab the addEvent, new, Bell, tm and 9000 and store it in a linkedlist. After reading through the whole text file I have to sort the the linked list based on the number. ie: 9000. Is there any way to do this? I currently break up the text file using a StringTokenizer object but then i am uncertain on how to add it to a linked list and then sort each line based on the number. Any help would be appreciated.
JoeSorry to bother you Ben but I just can't get my head wrapped around this. Here is exactly what I have to do:
After reading, Events must be stored in the EventSet according to the time they are to occur. Assume that no time number is more than 8 digits long. Restart() must be able to deal appropriately with any order of the Events. To accomplish this have Restart() save the relevant Event information in an LinkedList of strings and sort the Events by time before adding each event to EventSet. Use the <list>.add() to set up your linked list. This is shown in c09:List1.java and Collections.sort(<list>) shown in c09:ListSortSearch. Modify the Bell() to output a single "Bing!". When you read in a Bell event generate the appropriate number of Bell events as indicated by rings. These must be set to the correct times. This is an alternative to generating the new Bell events within Bell(). It will allow them be sorted into their correct time sequence. At this point the output of the program should be identical the original program.
After the intitial start, when restarting Restart() must provide to the user the option to recreate the EventSet from the linked list or read in a new file (supplied by the user). This must be achieved by prompting the user at the console. Please also allow the user the option to quit the program at this stage.
Main Program Code:
public class GreenhouseControls extends Controller
private boolean light = false;
private boolean water = false;
private String thermostat = "Day";
private boolean fans = false;
private class FansOn extends Event
public FansOn(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn on the Fans.
fans = true;
public String description()
return "Fan is On";
private class FansOff extends Event
public FansOff(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn off the Fans.
fans = false;
public String description()
return "Fans are Off";
private class LightOn extends Event
public LightOn(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn on the light.
light = true;
public String description()
return "Light is on";
private class LightOff extends Event
public LightOff(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here to
// physically turn off the light.
light = false;
public String description()
return "Light is off";
private class WaterOn extends Event
public WaterOn(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
water = true;
public String description()
return "Greenhouse water is on";
private class WaterOff extends Event
public WaterOff(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
water = false;
public String description()
return "Greenhouse water is off";
private class ThermostatNight extends Event
public ThermostatNight(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
thermostat = "Night";
public String description()
return "Thermostat on night setting";
private class ThermostatDay extends Event
public ThermostatDay(long eventTime)
super(eventTime);
public void action()
// Put hardware control code here
thermostat = "Day";
public String description()
return "Thermostat on day setting";
// An example of an action() that inserts a
// new one of itself into the event list:
private int rings;
private class Bell extends Event
public Bell(long eventTime)
super(eventTime);
public void action()
// Ring every 2 seconds, 'rings' times:
System.out.println("Bing!");
if(--rings > 0)
addEvent(new Bell(System.currentTimeMillis() + 2000));
public String description()
return "Ring bell";
private class Restart extends Event
public Restart(long eventTime)
super(eventTime);
public void action()
long tm = System.currentTimeMillis();
// Instead of hard-wiring, you could parse
// configuration information from a text
// file here:
try
BufferedReader in = new BufferedReader(new FileReader("Event Config.txt"));
String str;
String[] l1 = new String[5];
LinkedList l2 = new LinkedList();
while((str = in.readLine()) != null )
StringTokenizer st = new StringTokenizer(str, "(+); ");
int nIndex = 0;
while (st.hasMoreTokens())
l1[nIndex] = st.nextToken();
//System.out.println(st.nextToken());
nIndex++;
l2.add(l1);
String[] s1 = (String[])l2.get(1);
for(int i = 0; i < s1.length; i++)
System.out.println(s1);
Comparator comp = s1[4];
Collections.sort(l2, comp);
in.close();
catch (IOException e)
rings = 5;
addEvent(new ThermostatNight(tm));
addEvent(new LightOn(tm + 1000));
addEvent(new LightOff(tm + 2000));
addEvent(new WaterOn(tm + 3000));
addEvent(new WaterOff(tm + 8000));
addEvent(new Bell(tm + 9000));
addEvent(new ThermostatDay(tm + 10000));
// Can even add a Restart object!
addEvent(new Restart(tm + 20000));*/
public String description() {
return "Restarting system";
public static void main(String[] args) {
GreenhouseControls gc =
new GreenhouseControls();
long tm = System.currentTimeMillis();
gc.addEvent(gc.new Restart(tm));
gc.run();
} ///:~
Examples File:
addEvent(new ThermostatNight(tm));
addEvent(new Bell(tm + 9000));
addEvent(new Restart(tm + 20000));
addEvent(new LightOn(tm + 1000));
addEvent(new WaterOn(tm + 3000));
rings = 5;
addEvent(new FansOn(tm + 4000));
addEvent(new LightOff(tm + 2000));
addEvent(new FansOff(tm + 6000));
addEvent(new WaterOff(tm + 8000));
addEvent(new WindowMalfunction(tm + 15000));
addEvent(new ThermostatDay(tm + 10000));
EventSet.java Code:
// This is just a way to hold Event objects.
class EventSet {
private Event[] events = new Event[100];
private int index = 0;
private int next = 0;
public void add(Event e) {
if(index >= events.length)
return; // (In real life, throw exception)
events[index++] = e;
public Event getNext() {
boolean looped = false;
int start = next;
do {
next = (next + 1) % events.length;
// See if it has looped to the beginning:
if(start == next) looped = true;
// If it loops past start, the list
// is empty:
if((next == (start + 1) % events.length)
&& looped)
return null;
} while(events[next] == null);
return events[next];
public void removeCurrent() {
events[next] = null;
public class Controller {
private EventSet es = new EventSet();
public void addEvent(Event c) { es.add(c); }
public void run() {
Event e;
while((e = es.getNext()) != null) {
if(e.ready()) {
e.action();
System.out.println(e.description());
es.removeCurrent();
} ///:~
Event.java Code
abstract public class Event {
private long evtTime;
public Event(long eventTime) {
evtTime = eventTime;
public boolean ready() {
return System.currentTimeMillis() >= evtTime;
abstract public void action();
abstract public String description();
} ///:~
Is this problem easier than I think it is? I just don't know what to add to the linkedList. A LinkedList within a linkedList? I find this problem pretty difficult. Any help is muchly appreciated.
Joe -
Refresh cannel data from ever growing text-file
(I previously mis-posted this in the general forum, sorry!)
Hi,
I have text files coming in, each to add 250 values to a channel every 30 seconds. I am writing some code to massage the incoming data, and append the 4 channels to a single text file.
So I have 4 channels in a text file which continues to grow.
How do I make Diadem display all new data as the text file grows, to show analysis on the channel data in real-time?
Thanks!
My text file looks like this, and will grow by new lines as I receive them:
height,width,length,volume
15.00,13.460125,13.196651,12.123
13.404634,13.545893,13.171975,12.234
15.10,13.460125,13.196651,12.345
13.404634,13.545893,13.171975,12.456Hi Dave,
I thought you said in your other post that each quantity was in a file of its own? Well, if they're all in the same file that simplifies matters a bit. DIAdem does not have a built-in monitoring feature, but you could run a VBScript that re-loads the data up until now and runs the analysis and plots the report graphs, tables, etc. This would give you a periodically updating view into your ongoing data acquisition.
Note that there is an issue with ever-growing ASCII data files-- they take longer and longer to read. How big might these data files get? 10 MB? 100MB? 1GB? Really, if they're going to get bigger than a few MB you ought to consider segmenting them-- as your other post indicates they are. Then if time becomes an issue, the VBScript could keep track of which data files it's already loaded and only load the new ones.
Again, please send me the data files you have, and I'll make concrete suggestions,
Brad Turpin
DIAdem Product Support Engineer
National Instruments -
How to define and populate value to a variable in a text file
hi all,
i have a text file on unix server, when i read it through open dataset, is it possible to populate dynamic value to a variable in the text file. and is it possible to define a variable at any place in the text file?
after this the program will send the internal table for emailing.
thanks.Hi, If this file on server is a email template you can put some tags / marks and you can change it after you read it with OPEN DATASET / READ...
Sample:
OPEN DATASET p_file FOR INPUT IN TEXT MODE ENCODING DEFAULT.
CHECK sy-subrc EQ 0.
DO.
READ DATASET p_file INTO lv_string.
IF sy-subrc EQ 0.
EXIT.
ENDIF.
REPLACE ALL OCCURENCES OF '((SYSTEM_ID))' WITH sy-sysid.
APPEND input_file_tab.
ENDDO.
CLOSE DATASET p_file.
on file there's a line with:
This email was generated on server ((SYSTEM_ID))
It will be translated to (sy-sysid = DEV):
This email was generated on server DEV
This is a "variable" like that you can use. -
How to make the Open/Save dialogue download the text file instead of JSP
I am currently coding on a JSP program, which searches the database and writes the resultset into a file on the server, and then allows the client to download this tab delimited text file onto their local machine. But I met a problem, when the default Open or Save dialogue appears, it shows that it's trying to download the running JSP file from my local host instead of the newly-created text file. Despite this, when I click OK to either Open or Save the file, a warning dialogue will appear saying: The explorer cann't download this file, it's unable to find this internet site or something like that. I get no error message from the server but I was always told that Javax.servlet.ServletException: getWriter() was already called. What does this mean?
I guess maybe this is caused by the mix use of outputStreams in my program. I don't know if there is a way to directly read the resultset from the database and then send it through outputStream to the client. My solution is: first create a file on the server to hold the resultset, and then output this file to the client. I did all these in one JSP program: Create file on the server, search database, and then read file and output the contents to client. Is this correct? I attached my code, please feel free to correct any of my mistake? Thanks!
//global.class is a class dealing with database connection
<%@ page language="java" import="java.sql.*,java.util.*,java.math.*,java.io.*,ises.*,frmselection.*" %>
<jsp:useBean id="global" scope="session" class="ises.Global" />
/>
<!--start to process data-->
<%
//get query statement from the session
String sQuery = "";
if (session.getAttribute("sQuery")!=null && !(session.getAttribute("sQuery").toString()).equals(""))
sQuery = session.getAttribute("sQuery").toString();
String path = "c:/temp";
String fileName = "temp.TXT";
File file= null;
FileOutputStream fo = null;
PrintStream ps = null;
try {
file = new File(path,fileName);
if(file.exists()) {
file.delete();
file.createNewFile();
fo = new FileOutputStream(file);
ps = new PrintStream(fo);
}catch(IOException exp){
System.out.println("IO Exception: " +exp.toString() );
java.sql.ResultSet recResults = null;
java.sql.Statement STrecResults = null;
STrecResults = global.getConnection().createStatement();
recResults = STrecResults.executeQuery(sQuery);
ResultSetMetaData meta = recResults.getMetaData();
int columns = meta.getColumnCount();
String [] tempColumnName = new String[columns];
String [] ColumnName =null;
int DisColumns = 0;
int unDisCol = 0;
String sLine = "";
if(recResults.next()) { //if_1
for(int n=0;n<columns;n++) {
String temp = meta.getColumnName(n+1);
if(!temp.equals("PROJECTID")&&!temp.equals("BUILDINGID")&&!temp.equals("HAZMATPROFILEID")) {
sLine = sLine + "'" + temp + "'" + " ";
tempColumnName[DisColumns] = temp;
DisColumns ++;
ColumnName = new String[DisColumns];
}else {
unDisCol ++;
}//end for
for(int i=0;i<(columns-unDisCol);i++) {
ColumnName[i] = tempColumnName;
ps.println(sLine);
do{
sLine = "";
for(int n=0;n<(columns-unDisCol);n++) {
String tempColName = recResults.getString(ColumnName[n]);
if(tempColName==null) {
sLine = sLine + "" + " ";
} else {
sLine = sLine + "'"+tempColName+"'" + " ";
ps.println(sLine);
}while(recResults.next());
} //end if_1
recResults.close();
recResults = null;
STrecResults.close();
STrecResults = null;
%>
<!--end of processing data-->
<!--start of download.jsp-->
<%
//set the content type to text
response.setContentType ("plain/text");
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment;filename=temp.TXT");
//Open an input stream to the file and post the file contents thru the servlet output stream to the client
InputStream in = new FileInputStream(file);
ServletOutputStream outs = response.getOutputStream();
int bit = 256;
try {
while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
outs.flush();
outs.close();
in.close();
%>
<!--end of download -->Thanks. I believe something wrong with this statement
in my program:
You are correct there is something wrong with this statement. Seeing how you are doing this in a jsp, not really what they're made for but thats another topic, the output stream has already been called. When a jsp gets compiled it creates a few implicit objects, one of them being the outputstream out, and it does this by calling the response.getWriter(). getWriter or getOutputStream can only be called once, other wise you will get the exception you are experiencing. This is for both methods as well, seeing how the jsp compiles and calls getWriter means that you cannot call getOutputStream. Calling one makes the other throw the exception if called as well. As far as the filename problem in the browser goes I'm guessing that it's in IE. I've had some problems before when I had to send files to the browser through a servlet and remember having to set an inline attribute of some sort in the content-dis header inorder to get IE to see the real filename. The best way to solve this is to get the orielly file package and use that. It is very easy to use and understand and does all of this for you already. Plus it's free. Cant beat that.
ServletOutputStream outs =
response.getOutputStream();
because I put a lot of printout statement within my
code, and the program stops to print out exactly
before the above statement. And then I get the
following message, which repeats several times:
ServletExec: caught exception -
javax.servlet.ServletException: getWriter() was
already called. -
How to adjust splitted lines into one line in Text file?
Hi Guys,
I have a text file with 3 fields(comma separated): GLCode (Number), Desc1 (Char), Desc2(Char) and need to load it into BW.
My Text file looks like:
1011.00,"Mejor PC Infrastructure","This line is ok."
1012.00,"Telephone Equipment $","This line ends in next line.
1)Need to change the equipment immediately.
2)Take immediate action"
1013.00,"V1 Computer Server Infrastructure # Equip","For purchases
of components that make up the company's network, such as servers, hubs, routers etc."
1014.00,"Flash Drive","Need to provide all IT Developer"
This is how file looks like. Now I need the followings:
1. Need to remove the space and need to adjust the splitted line into one. Say here
line/record 2 is splitted into 3 lines and need to adjust in 1 line.
2. In Line 5 (Record 3) data splitted into 2 lines and need to make 1 line.
3. Need to remove bad characters.
Could someone help me please how to proceed ?
Regards,Not quite correct by my testing. Try:
$i=0
Get-Content .\test.txt | ForEach {
If ($i%2){
("$Keep $($_)").Trim()
}Else{
$keep=$_
}$i++
Good catch!
Boe Prox
Blog |
Twitter
PoshWSUS |
PoshPAIG | PoshChat |
PoshEventUI
PowerShell Deep Dives Book -
Help with 2D array input using a text file
I'm writing a JAva program using BlueJ, which requires me to read info from a text file and put them into an 2D array. I got this error msg and I couldn't gifure out how to fix it. Please help me. Thanks a lot. The program is due tomorrow, please help.
Error message:
NoSuchElementException:
null(in Java.util.StringTokenizer)
Here's the program with the line where the problem is highlighted
import java.io.*;
import java.util.StringTokenizer;
public class ***
// Reads students' test scores from a file and calculate their final grade
public static void main (String[] args) throws IOException
String file1 = "C:/Temp/scores.txt";
int[][] input = new int[25][5];
StringTokenizer tokenizer;
String line;
FileReader fr = new FileReader (file1);
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
tokenizer = new StringTokenizer (line);
for (int row = 0; row < 25; row++)
for (int col = 0; col < 5; col++)
input[row][col] = Integer.parseInt(tokenizer.nextToken()); --> porblem
This is what the text file looks like:
1 74 85 98
2 97 76 92
3 87 86 77
4 73 85 93
5 99 99 83
6 82 84 95
7 78 83 91
8 84 79 84
9 83 77 90
10 75 78 87
11 98 79 92
12 70 73 95
13 69 80 88
14 81 77 93
15 86 72 80
16 70 76 89
17 71 71 96
18 97 81 89
19 82 90 96
20 95 85 95
21 91 82 88
22 72 94 94Try this code..(I've tested this code in my machine and it works fine)
try {
FileReader fileReader = new FileReader("Z:\\fileInput.txt");
BufferedReader reader = new BufferedReader(fileReader);
int[][] fileData = new int[22][4];
StringTokenizer tokenizer = null;
String line = reader.readLine();
int rowCount = 0;
while(line != null) {
tokenizer = new StringTokenizer(line, " ");
int columnCount = 0;
while(tokenizer.hasMoreTokens()) {
fileData[rowCount][columnCount] = Integer.valueOf(tokenizer.nextToken()).intValue();
columnCount++;
line = reader.readLine();
rowCount++;
fileReader.close();
System.out.println("Done");
} catch (FileNotFoundException fnfe) {
System.out.println("File not found " + fnfe);
} catch (IOException ioe) {
System.out.println("IO Exception " + ioe);
The problem with your code is that you should first check whether there are any tokens before doing nextToken().
-Amit
Maybe you are looking for
-
after the newest update ( iso 7) , i can no longer type in traditional chinese ( pin yin), does anyone else have the same problem?
-
Can somebody explain what is LUW ?
Hi Gurus, can somebosy explain me what is LUW(Logical unit of work). I went through some book, but i am not able to get the concept. can somebody help me out inthis Thanks & regards Rajesh Meda
-
Why does Aperture implement full screen mode differently to other Apple software?
Yes I know I always was pretty thick, and things haven't improved as senility draws nigh, but I have not yet found a way to run Aperture as I would like to. What I want to do is to run the NON full-screen interface in a manner that occupies the whole
-
Errors when reinstalling windows from recovery disks
My laptop crashed and could no longer find Windows, so I ordered a recovery disc (TR-IM00209299 - Win7 SP1 64Bit HomePremium (NH)) via the Toshiba Recovery Media Shop. I have now received the Windows 7 Recovery discs but they do not successfully inst
-
Documentation Types in projects
Is it possible to differentiate Documentation Types selectable in RMMAIN and Solar01/02 ? The reason we want this is that we produce project documentation (sub set of the Documentation Types) in RMMAIN and we produce the Solution documentation (anoth