A line of text, tokenizing it using StringTokenizer
Hello,
I feel I'm going round in circles, what I have is a line of text a mobile message like these
25 100
SEND 2228161 Hello Pete
RECEIVE 2228161 Hello Chris, how are you?
SEND 2227765 I hate text speak
RECEIVE 2228876 wot u on bout
SEND 2227975 The quick brown fox jumped over the lazy dog
SEND 2328161 Simple Simon met a pieman going to the fair
I'm to extract the message and check it's length, to then put in an array not an ArrayList if it's greater than 25, break it up into tokens. Is this how StringTokenizer works the SEND part is token 1, the mobile number is token 2 and the message is token 3. Or am I making it more difficult than it sounds? Should I just use String.split() method (which I'm confused on how to use). Another question BlueJ seems to read the file and then hang, I have to reset the machine, should,'t I have an EOF somewhere, because I thought I've closed the file here.
Here's the code so far, the file reads in OK, I get the ouput, for checking purposes
Public class Driver2
public static void main(String[] args)
//read the file
BufferedReader reader = null;
StringTokenizer tokens = null;
String line = null;
try
reader = new BufferedReader(new FileReader(args[0]));
line = reader.readLine();
while ((line = reader.readLine()) != null)// read each line until null is returned
{ // line will be null when we reach end of the file
int i = 0;
// process data
tokens = new StringTokenizer(line, "");
while (tokens.hasMoreTokens())
//get next token
System.out.println(tokens.nextToken());
//(line = reader.readLine()) != null
// split on the white space with eiher RECEIVE or SEND before it
String[] storeTokens = line.split("(SEND|RECEIVE)\\s");
//("(?<=RECEIVE|SEND)\\s");
if (line.startsWith("SEND"))
System.out.println("SEND message");
if ((storeTokens[1].length()) > 25)
System.out.println("This too big");
String[] tempTokens = line.split("(?<=SEND)\\s");
System.out.println("Message has been: "+tempTokens[0]);
System.out.println("\tmessage = "+tempTokens[1]+"\n\tlength = "+tempTokens[1].length());
if (line.startsWith("RECEIVE"))
System.out.println("RECEIVE message");
if (line.startsWith("DELETE"))
System.out.println("DELETE message");
if (line.startsWith("VIEW"))
System.out.println("VIEW message");
reader.close();
catch( FileNotFoundException filenotfoundexxption )
System.out.println( "File not found" );
catch( IOException ioexception )
ioexception.printStackTrace( );
}// close main
}// End of classThanks in advance
Hello,
I am trying to strip out the SEND word and telephone number, leaving me a String to then test the length of and if it's greater than 25 characaters, split it up a number of times and store back into the array.
message is:
SEND 2226543 Mary had a little lamb, its fleece was white as snow
The code I used for the String split works, it returns this String - String[] sendTokens = line.split("\\SEND|[0-9]");Mary had a little lamb, its fleece was white as snow
I then have to test for the String length, in this case it is 52 characters, split this up into 3 separate strings thus:
Mary had a little lamb, i
ts fleece was white as sn
ow
I think I have to use the line.length => 25, then split the message up
What's wrong with the split method, I've used? I've tried every combination, this seems to work, although there are large gaps in the output, like this.
Christmas is coming the geese are getting fat
SEND message
Cristiano Ronaldo plays for Portugal
SEND message
Thanks for the advice
Similar Messages
-
How to read line number text from PDF using plugin?
Hi, I would like to know how to read line number text from PDF using plugin?
Thanks in advance.Ok, some background reading of the PDF Reference will help you understand why this is so difficult. PDF files are not organised into lines. It is best to think of each word or character on the page as being a graphic with its own position. The human eye sees lines where a series of graphics (words) are roughly in the same horizontal region.
In the general case it is difficult or even impossible to answer this. You may have columns with different spacing (but the PDF stores no information on what is a column). You may have subscripts and superscripts. You may have text in graphics coinciding with other text. Commonly, there may be titles, headings or page numbers which are just ordinary text and might count as lines.
That said, what you need to do is extract the text on the page and its positions. The WordFinder APIs are the way to do that. Now, sort all the words out, using the Y coordinates and size to try and guess what makes a "line". Now you are in a position to find the text (divided into words, not strings) and report the "line number" you have estimated. -
Reading a file line by line from right to left using StringTokenizer
I hope the title caught you attention!!!
I am a little stuck. How can I implement a method that will allow me to read a sentence from right to left when reading from file.
Ex.
IX: Series {2}
IX: {Series!geometric|(} {4}
IX: {Euler's constant} {4}
IX: {Series!geometric|)} {4}
IX: {Series!arithmetic|(} {4}
IX: {Series!arithmetic|)} {5}
IX: {Series!harmonic|(} {5}
IX: {Euler's constant} {5}
IX: {Series!harmonic|)} {5}
IX: Series {5}
So for example in the first row we have
IX: Series {2}
and what the output should show be is
Series: 2
What happens in the background is that I created an entry for a TreeMap which will be display at the end.
Thanks for your time and appreciate your help kindly.Well, as a left-to-right start:
public class TopicInputReader extends BufferedReader {
public static final int STARTTOPIC = 0;
public static final int ENDTOPIC = 1;
public static final int SUBTOPIC = 2;
// Instead of making Topic members public, you should make accessors.
// Didn't feel like typing.
public class Topic {
public int type; // STARTTOPIC, ENDTOPIC, or SUBTOPIC
public String name;
public String parent;
public int page;
public TopicInputReader (Reader in) {
super(in);
public TopicInputReader (Reader in, int sz) {
super(in, sz);
public Topic readTopic () throws IOEXception {
String line;
Topic topic;
StringTokenizer tokens;
String token;
line = readLine();
if (line = null) throw new EOFException();
tokens = new StringTokenizer(line);
topic.parent = "".intern();
// Note: If StringTokenizer isn't appropriate for you, you
// can use a StringReader in conjunction with a StreamTokenizer.
// Ex: token = new StreamTokenizer(new StringReader(line));
// TODO: Set up tokenizer parameters here.
while (tokens.hasMoreTokens()) {
token = tokens.nextToken(appropriate_delimiter);
// TODO: Fill in 'topic' fields here.
// Keep in mind, since you're reading left-to-right and you don't
// know if a particular string is going to be a topic name or a
// sub topic, you can always just read a topic name into topic.name
// and, when you encounter a new topic name:
// topic.parent += ('!' + topic.name);
// topic.name = token;
return topic;
};I definitely have not tested that... or even double-checked it.
Although... the format of your topic list file does lend itself well to right-to-left parsing. Since you are insisting, I suggest reversing the string and using a StringTokenizer (or a StreamTokenizer and a StringReader):
BufferedReader r = new BufferedReader(new InputStreamReader(myInputStream));
String line, revline;
StreamTokenizer tokens;
while (...) {
line = r.readLine();
revline = (new StringBuffer(line)).reverse().toString();
tokens = new StreamTokenizer(new StringReader(line));
// Parse tokens here.
};Jason -
Urgent! How to display more than 1 line of text in SAPSCRIPT using tab
Hi, i would like to know how do i display all the text (which may consist of more than 1 line) that i have extracted using a READ_TEXT FM in my print program? Once the text has been extracted and displayed, i would like the proceeding lines of text (if there are more than 1 line) to begin at a certain margin (i have defined a paragraph format as 6.2cm in tab option).
Have a look at the part of the print program that has the READ_TEXT FM statements which is going to extract the text from the PR Document header:
LOOP AT ITAB.
CLEAR: PR_TXT, PR_TXT[].
L_NAME = ITAB-BANFN.
CALL FUNCTION 'READ_TEXT'
EXPORTING
CLIENT = SY-MANDT
ID = 'B01'
LANGUAGE = SY-LANGU
NAME = L_NAME
OBJECT = 'EBANH'
ARCHIVE_HANDLE = 0
* LOCAL_CAT =
TABLES
LINES = PR_TXT
EXCEPTIONS
ID = 1
LANGUAGE = 2
NAME = 3
NOT_FOUND = 4
OBJECT = 5
REFERENCE_CHECK = 6
WRONG_ACCESS_TO_ARCHIVE = 7
OTHERS = 8.
LOOP AT PR_TXT.
MOVE: ITAB-BANFN TO PTXT_TAB-BANFN,
SY-TABIX TO PTXT_TAB-POSNR,
PR_TXT-TDLINE TO PTXT_TAB-LINE.
APPEND PTXT_TAB.
ENDLOOP.
As for my SAPSCRIPT, i did the following:
* Purchase Request Header : &PTXT_TAB-LINE(C)&
I would like all of the proceeding lines of text to appear at the same margin as when the first line of &PTXT_TAB-LINE& started (which i have found out is 6.2cm, so i created a tab called HT for this)
Message was edited by: Bernard LohREPORT ZZZZANC9 .
tables mara.
data: i_mara like mara occurs 0 with header line.
select matnr from mara
up to 100 rows
into corresponding fields of table i_mara
where matnr ne space.
CALL FUNCTION 'OPEN_FORM'
EXPORTING
APPLICATION = 'TX'
ARCHIVE_INDEX =
ARCHIVE_PARAMS =
DEVICE = 'PRINTER'
DIALOG = 'X'
FORM = 'ZZZZANC1'
LANGUAGE = SY-LANGU
OPTIONS =
MAIL_SENDER =
MAIL_RECIPIENT =
MAIL_APPL_OBJECT =
RAW_DATA_INTERFACE = '*'
IMPORTING
LANGUAGE =
NEW_ARCHIVE_PARAMS =
RESULT =
EXCEPTIONS
CANCELED = 1
DEVICE = 2
FORM = 3
OPTIONS = 4
UNCLOSED = 5
MAIL_OPTIONS = 6
ARCHIVE_ERROR = 7
INVALID_FAX_NUMBER = 8
MORE_PARAMS_NEEDED_IN_BATCH = 9
SPOOL_ERROR = 10
OTHERS = 11.
IF sy-subrc <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
loop at i_mara.
mara-matnr = i_mara-matnr.
CALL FUNCTION 'WRITE_FORM'
EXPORTING
ELEMENT = 'MATERIAL'
FUNCTION = 'SET'
TYPE = 'BODY'
WINDOW = 'MAIN'
IMPORTING
PENDING_LINES =
EXCEPTIONS
ELEMENT = 1
FUNCTION = 2
TYPE = 3
UNOPENED = 4
UNSTARTED = 5
WINDOW = 6
BAD_PAGEFORMAT_FOR_PRINT = 7
SPOOL_ERROR = 8
OTHERS = 9
IF sy-subrc <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
endloop.
CALL FUNCTION 'CLOSE_FORM'
IMPORTING
RESULT =
RDI_RESULT =
TABLES
OTFDATA =
EXCEPTIONS
UNOPENED = 1
BAD_PAGEFORMAT_FOR_PRINT = 2
SEND_ERROR = 3
SPOOL_ERROR = 4
OTHERS = 5
IF sy-subrc <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
Look through above code. Sapscript should contain a text element (/E control) as below
/E MATERIAL
&mara-matnr& -
How do I get rid of various lines around text boxes when using navigation panes
How can I get rid of these various lines that are displaying sporatically around different text boxes . . . but only when the navigation panel is displaying? I previously had the issue and changed the text box properties to no fill. It fixed the problem in the document with no navigation panel, but once the navigation panel is displayed the lines appear. And yes, I fixed the text box properties before creating the bookmarks for the navigation panel.
Every device, browser and browser version has its idiosyncrasies.
Just using a stroke and a drop shadow should not have been enough to require Muse to convert the page fill to an image. Were/are there also other effects on the page? Are the page corners slightly rounded?
Bevel and Inner Glow definitely require an image to be created. Most other effects/properties do not. -
How to drag component from data control palette and drop in a line of text?
Hi,
I am using JDeveloper 10.1.3.4 and get frustrated with my attempt to drag a component from the data control palette and drop it in a line of text in a .jspx page. What I need to accomplish is to display a line of text to the use on a page:
Get clearance for the Spring 2009 semester.This is a line of static text except "Spring 2009" is the {color:green}Term{color} attribute of a view object dragged from the data control palette. I found that if I try to type some text on a page, as soon as I create a new line, a <f:verbatim> is created. So when I tryped the first part of the text, the code is:
<f:verbatim>
<p>
Get clearance for the
</p>
</f:verbatim>Then drag-and-drop the bound data from the data control palette:
<f:verbatim>
<p>
Get clearance for the
<af:outputText value="#{bindings.Term.inputValue}"
binding="#{backing_student_printOrQuit.outputText6}"
id="outputText6"/>
</p>
</f:verbatim>And then add the last word:
<f:verbatim>
<p>
Get clearance for the
<af:outputText value="#{bindings.Term.inputValue}"
binding="#{backing_student_printOrQuit.outputText6}"
id="outputText6"/> term.
</p>
</f:verbatim>This looks OK in the Source tab. But in the Design tab the bound data jumps above the text line. Both the bound data and the <f:verbatim> appear to be block elements in the page. And so is it when the line is displayed in the browser:
Spring 2009
Get clearance for the term.How to overcome this problem?
Thanks for sharing your experience.
NewmanShay,
Waht a surprise! Just now I had already finished typing the posting to tell that it did not work. I tried changing the original code to
<f:verbatim>
<p>
Get clearance for the #{bindings.Term.inputValue} term.
</p>
</f:verbatim>and got the display:
Get clearance for the #{bindings.Term.inputValue} term.I tried various ways, putting single quotes around the whole expression in single quotes, around part of it, using square brackets, ... I was going to click the "Post Message" button, but gave it one last try:
<f:verbatim>
<p>
Get clearance for the ${bindings.Term.inputValue} term.
</p>
</f:verbatim>and I got it! --
Get clearance for the Spring 2009 term.It was my gut feeling that I was quite close because the dot-separated hierarchy {color:green}bindings.Term.inputValue{color} looks right, only some tiny bit in syntax narrowly missing it. I was lucky.
Thank you for the suggestion!
Newman -
Multiple Lines of Text For Each Clip in Project Panel
Premiere CC latest update. Mac Mavericks
I would like to disply multiple lines of text for each clip in the Project Panel.
I have a couple paragraphs in the Description box, and I would like to be able to read all the text in the Description box.
As it stands, it is very difficult to read more than one sentence in the Description box.
Is there any way that I can view all the text in the Description box?Hi sats_sandy,
To keep some tags and remove unused tags in the schemaxml file the multiple line of text, you can use regular expression to remove the unwanted tags.
Here is a sample code snippet:
private static string RemoveSpecifyHtml(string ctx) {
string[] holdTags = { "a", "img", "br", "strong", "b", "span" };//tags to be reserved
// <(?!((/?\s?li)|(/?\s?ul)|(/?\s?a)|(/?\s?img)|(/?\s?br)|(/?\s?span)|(/?\s?b)))[^>]+>
string regStr = string.Format(@"<(?!((/?\s?{0})))[^>]+>", string.Join(@")|(/?\s?", holdTags));
Regex reg = new Regex(regStr, RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
return reg.Replace(ctx, "");
Thanks,
Qiao Wei
TechNet Community Support -
More than 1 line of text when using text generator from file?
hi
have 8 line blocks of text to show onscreen.
would like to use text generatorn>from file
all they seem to print is one line.
is there a work around?
have trhied soft returns and paragraphs on saved text file.
no change.
anyonre know how to get 2 or more lines of text?
thanks in addvance!Select the File generator layer and in the Inspector, select the Layout pane and in Layout controls, set the Layout Method to Paragraph. Narrow your margins and the text will "flow" into multiple lines.
You can also keyframe the paragraph layout position. [Probably more info than you want here.]
That said, you can only display *one line* at a time per File Generator. (If you're up to date with Motion [v5.1.2], you can use more than one File generator.) The generator does not accept any other characters for returns other than newline and carriage return.
I've never tried it, but thinking about it, you can set Tab stops in the Paragraph layout (double click in the layout rectangle and a ruler should appear over the top -- right click on the ruler to set tabs). If you go back into the original text file and where you need to break lines into two or more, setting a left tab stop in the layout very near the end of a line might force the tabbed text into the next line (did I make that clear enough??) -
Reading Individual Lines of Text Into An ArrayList or Vector From A File
I am trying to read each individual line of text of a .txt file into an ArrayList or Vector. I seem to get the same results no matter which Object I am using (ArrayList or Vector). The text file is a comma-delimited text file to be used as a database. I want to separate each line as an individual record then dump it into an ArrayList or Vector and have them loop through a StringTokenizer() class so that I can be sure each line has the correct number of fields before I commit it to a serialization file. Currently, the proper amount of records seems to be forming in the initial part of the program, I am just remiss at properly placing them in the Vector, or StringTokenizer classes so I can further manipulate them. I'm using the LineNumberReader class to get line numbers to use as record numbers and for loop indexes. I'm not sure (obviously) if this is a correct way to do it or not.
Any help is greatly appreciated in advance.
Thanks for all your time.
int n = 0;
try {
* read each individual line and count it as a separate record.
* place each record into an array or may be a string if it has 9 tokens
* if a record hasn't got 9 tokens, it isn't a record
* place each array or string into a Vector
in = new LineNumberReader(new FileReader(filename));
while ((record = in.readLine()) != null) {
n = in.getLineNumber();
rawData = new Vector();
for (int i = 0; i < n; i++) {
rawData.add(record);
if (record == null)
break;
*The following System.out.println() statement shows that all lines are correctly retrieved from the text file
*as separate records
System.out.println("Record No. " + n + "= " + record);
//Debug
/** When these print lines execute it reveals that only the last record has been inserted into the Vector as
* many times as I have records in the text file.
System.out.println("Number of Records = " + n);
System.out.println("VectorSize = " + rawData.size());
System.out.println("First rawDataElement = " + rawData.firstElement());
System.out.println("Second rawDataElement = " + rawData.get(1));
System.out.println("Third rawDataElement = " + rawData.get(2));
System.out.println("Fourth rawDataElement = " + rawData.lastElement());
* Next run each record through a StringTokenizer to be sure that there the correct number of fields present
* If it contains the correct number of fields, dump it into an alternate ArrayList or Vector.
* As it is now, the StringTokenizer gives a NullPointerException
for (int i = 0; i < n; i++) {
StringTokenizer recordSet = new StringTokenizer((String) table.get(n), ",");
while (recordSet.hasMoreTokens()) {
if (recordSet.countTokens() == 9) {
data = new Vector();
data.add((Object) recordSet.nextToken(","));
System.out.println("Vector data size = " + data.size());
System.out.println("Second dataElement = " + data.get(0));
System.out.println("String Tok recordSet = " + recordSet.countTokens()); System.out.println("Number of Records = " + n);
System.out.println("First dataElement = " + data.firstElement());
System.out.println("Second dataElement = " + data.get(0));
System.out.println("Third dataElement = " + data.get(2));
System.out.println("Fourth dataElement = " + data.lastElement());
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}I think your logic is broken.
rawData = new Vector();
creates a new instance of Vector for every record.
Your add() within a for loop adds the same record to the Vector n times. I think what you really want is something like this:in = new LineNumberReader(new FileReader(filename));
rawData = new Vector();
while ((record = in.readLine()) != null) {
n = in.getLineNumber();
rawData.add(record); Mark -
Reading in a line of text and breaking it up, complicated
Hi all,
At the moment im reading in a few 100 lines of text from a file, each line contains a command and a few variables which need to be set to existing variables I have created shown below;
Int variableA ;
Int variable B ;
Int variable C;
Int Variable D;
However I have no way to know which command will go with which variables,
On every line there will be one command and two variables..
The possible command are; ADD, SUB, TIMES, Divide, COPY, SET
And the text coming in look like this;
SET A10, B15 // set each variable
SET C33, D50 // as above
COPY A, B // which means assign copy what ever in variableA to variableB
ADD C, D // which mean add variableC�s contents to variableD contents
SUB B, C // which is subtract variableC contents by what ever is in variableB
Does anybody know of a way where I can test what the next command is, and assign the correspond variables , so far I have come up with;
But am not sure if this is the best way to go about it, was thinking maybe I should put the text file into an array, which might make it easyer to process.
public static void main (String [] args)
int D = 0 ;
int C = 0 ;
int B = 0 ;
int A = 0 ;
StringTokenizer st ;
String line ;
String buffer = "";
String file ="test2.txt" ;
String name = "";
String billy = "";
try
FileReader fr = new FileReader(file) ;
BufferedReader inFile = new BufferedReader (fr) ;
//read in one line @ a time
buffer =inFile.readLine() ;
while (buffer !=null)
StringTokenizer words = new StringTokenizer (buffer) ;
//put the buffer "line" into a tokenizer for individual characters out of a line;
while(words.hasMoreTokens())
String letter = words.nextToken() ;
if(letter.charAt (0) == 'S') // if first letter = S would be SET
System.out.println(letter) ;
//display the token as a test output;
if(letter.charAt (0) == 'A') // if letter = A would be ADD
System.out.println(letter) ;
buffer = inFile.readLine() ;
//read in next line
inFile.close();
catch (FileNotFoundException e)
System.out.println("File not found");
catch ( IOException e)
System.out.println("IO Exception") ;
}hi,
i think that what u r tring to do is "parsing" where u translate these primatin=ve commands to execute them, if so here what u need to do:
Rad a line untell end of file
for each token in the line
if(token="SET" || token="ADD || token=""SUB")
{ //save operation for later use
operation=token;
//now u expect the next token to be an operand
token=nextToken;
if (token!="" and token!=",")//it must be an operand
{operand1=token;
token=next token;
if(token=",")//do nothing just read the nest operand
token=nexttoken;
else //syntax error in file, exit ;
if (token!="" and token!=",")//checking the 2nd operand
operand2=token;
//now check value of operation and call the right method and send operand1,operand2 as arguments to get the result e.g
if(opration=="ADD")
system.println("result of addition is"+addMethod(operand1,operand2));
hope that helps,
Insighter -
Problem with Java assignment using StringTokenizer
I am having trouble with a Java assignment. The objective is to take a user-defined sentence, split each word up, and put each word on a line. Then the program extracts the vowels and prints them to the end of the word in the order they appeared. The program, when properly done, looks like this:
Enter a line of text: Early in the morning 'bout the break of day
rlEay
ni
the
mrnngoi
'btou
the
brkea
fo
day
I can't figure out how to take the vowels and put them at the end of the word. So far my code looks like this:
import java.io.*;
import java.util.*;
class WordPlay
public static void main (String[] args) throws IOException
// ========================= //
// Declaration of variables. //
// ========================= //
int count;
BufferedReader keyboard;
String oneWord;
String sentence;
String spaces;
String vowels;
StringTokenizer words;
// ================================== //
// Introduction and user orientation. //
// ================================== //
System.out.print ("Enter a line of text: ");
// ============================ //
// Initialization of variables. //
// ============================ //
keyboard = new BufferedReader (new InputStreamReader(System.in));
sentence = keyboard.readLine();
spaces = " ";
words = new StringTokenizer(sentence,spaces);
// ================= //
// Logic statements. //
// ================= //
while (words.countTokens() > 0)
oneWord = words.nextToken();
vowels = "A,a,E,e,I,i,O,o,U,u,Y,y";
count = 0;
System.out.println(" " + oneWord);
I know that I need to use a StringTokenizer method to break each word's characters up and extract the vowels, but I don't know the right way to do this. My instructor stated that the program uses 2 while statements and an if statement, in that order. Problem is that I don't know how to proceed from here. Can anyone point me in the right direction?
Let me know if you want anything clarified. I apologize for the verbose code; my instructor doesn't let us take any shortcuts.Hey, thanks for replying, but I'm still confused about one thing.
If I'm not mistaken, the program when executed takes each word that I separated with StringTokenizer and prints the consonants and then moves on. How can I get Java to store the vowels only for the amount of time needed to concatenate them to the end of the word? I would think a while loop would solve the problem, but as my code is set up, the sentence is tokenized to only words. How do I properly break down the words into characters? I would think that another StringTokenizer could do this, but it seems to me that one StringTokenizer will override the other one, yet I need each word separated as well.
Can you offer any advice on that? -
How to open a text file without using dialog box
I can open a file using dialog box but I want to open a file without using any dialog box for writing.
With the following commands a new file is created.
File outputFile = new File("outagain.txt");
FileWriter out = new FileWriter(outputFile);
I want to open an existing file and put some more text in it using FileWriter or any other object
rgds,
Arsalanimport java.io.*;
class UReader
BufferedReader in;
BufferedReader input;
String fileName;
public UReader(String fileName)
this.fileName = null;
this.fileName = fileName;
try
in = new BufferedReader(new FileReader(fileName));
input = new BufferedReader(new FileReader("A.b"));
catch(IOException _ex) { }
public final String getContent()
String txt = "";
try
while(in.ready())
txt = txt + in.readLine();
txt = txt + "\n";
in.close();
txt.trim();
catch(IOException _ex) { }
return txt;
public final String getLine(int row)
try
input = new BufferedReader(new FileReader(fileName));
catch(IOException _ex) { }
String txt = null;
if(row <= getRows()) {
try
for(int i = 0; i < row; i++)
txt = input.readLine();
input.close();
catch(IOException _ex) { }
} else {
txt = "Index out of Bounds";
return txt;
public final int getRows()
try
input = new BufferedReader(new FileReader(fileName));
catch(IOException _ex) { }
String txt = null;
int rows = 0;
try
while(input.ready())
txt = input.readLine();
rows++;
input.close();
catch(IOException _ex) { }
return rows;
import java.io.*;
import java.util.*;
class UWriter
PrintWriter out;
String fileName;
String[] txt;
static int NEW_LINE = 1;
static int APPEND = 0;
public UWriter(String s)
fileName = null;
txt = null;
fileName = s;
try
out = new PrintWriter(new BufferedWriter(new FileWriter(s, true)));
catch(IOException ioexception) { }
public final void addContent(String s, int i)
int l = 0;
StringBuffer sb = new StringBuffer(s);
s.replaceAll("\n\n", "\n###\n");
StringTokenizer str = new StringTokenizer(s, "\n");
String token = null;
while (str.hasMoreTokens()) {
++l;
token = str.nextToken();
str = new StringTokenizer(s, "\n");
txt = new String[l];
int k = 0;
String test;
while (str.hasMoreTokens()) {
test = str.nextToken();
if (test.equals("###")) test = "";
txt[k++] = test;
if(i == 0) {
try
for (int j = 0; j < txt.length; ++j) {
out.println(txt[j]);
out.close();
catch(Exception ioexception) { }
} else {
try
out.println();
for (int j = 0; j < txt.length; ++j) {
out.println(txt[j]);
out.close();
catch(Exception ioexception1) { }
public final void writeContent(String s)
int l = 0;
s.replaceAll("\n\n", "###");
StringTokenizer str = new StringTokenizer(s, "\n");
String token = null;
while (str.hasMoreTokens()) {
++l;
token = str.nextToken();
str = new StringTokenizer(s, "\n");
txt = new String[l];
int k = 0;
String test;
while (str.hasMoreTokens()) {
test = str.nextToken();
if (test.equals("###")) test = "";
txt[k++] = test;
try
PrintWriter bufferedwriter = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
for (int j = 0; j < txt.length; ++j) {
bufferedwriter.println(txt[j]);
bufferedwriter.close();
catch(IOException ioexception) { }
}Maybe they are not the best codes, i wrote them a long time ago, so dont ask why i did anything wierd. :D
But anyway it works. -
How to Exclude Java Reserved Words Using StringTokenizer
Hi, i'm trying to exclude identifiers and java reserved words using StringTokenizer from an input file outputting the remaining words alphabetically ordered with the line, on witch they occur, in front of the word.
So far my code does all that, except exclude those words. I'm kind on a dead end... Any suggestions?
The code:
public class Interpreter{
/* Uses a Binary Search Tree */
public static void main(String args[ ]) {
String path = null;
for (int j = 0; j < args.length; j++) {
try {
// Step 1, read the input file
path = args[j];
FileReader input = new FileReader(args[j]);
BufferedReader br = new BufferedReader(input);
String line;
int count = 1;
String word;
// Step 2, create an empty Tree
BST tree = new BST();
while((line = br.readLine())!=null){
StringTokenizer str = new StringTokenizer(line);
while (str.hasMoreTokens()){
word = str.nextToken();
tree.insert(word,count);
count++;
// We're done, print out contents of Tree!
tree.print();
// Error Handling
//check for IO problem with bad file
} catch (IOException e) {
System.out.println("There was a problem with the filename you entered.");
//check for no filename entered at command prompt
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please include a filename when running this program.");
}Edited by: Redol on Dec 12, 2007 8:32 PM
Edited by: Redol on Dec 12, 2007 8:33 PMuse split instead of tokenizer.
public String[] splitString( String line, String delim )
String[] tokens = null;
if( line != null )
tokens = line.split( delim );
return tokens;
} -
Document line item text in Clearing document
Dear All,
Document line item text
My client want the vendor invoice line item text(BSIK-SGTXT) to be captured in the corresponding clearing document line item text field(BSAK-SGTXT).
(i.e) The vendor invoice and its payment clearing document should have the same text in the document line item text filed.
According to me i can use a substition rule and a user exit to assign the values. but here comes a problem* i have one clearing document against 3 to 4 vendor invoice documents* so my programming logic has got stucked here? like which vendor invoice line item text the clearing document should pick up?
is there any other enhancements possible or can some one help me with the programming logic to be applied here.
Thank you
Regards,
Vasanth Dlike which vendor invoice line item text the clearing document should pick up?
is there any other enhancements possible or can some one help me with the programming logic to be applied here
Why don't you discuss the issue with your client? As you said, if you pay 5 invoices in a single run, the payment document item text can't carry all of those texts unless you use the long text. What is the reason for the requirement? Perhaps there's another solution. -
We keep many logs in a simple list format. One of the columns requires a description using the "multiple lines of text" default column. Sometimes the person making the entry needs to complete about 20-30 lines of text. Users are requesting we reduce
the amount of space advanced between lines to save space and be more concise. Is there a way to reduce the line spacing for the column entries to single spacing without code?
Maree N PercivalWe determined that the site column settings were incorrect for allowing single spacing, we changed the site column setting from "Enhanced rich text (Rich text with pictures, tables, and hyperlinks)" to "Rich text (Bold, italics, text alignment, hyperlinks)"
and it is now keeping the text in single spaced lines.
<label for="onetidRichText">Specify the type of text to allow:</label>
<input id="onetidRichTextPlain" name="RichText" title="Plain text" type="radio" value="PLAIN" />
<label for="onetidRichTextPlain">Plain text </label>
<input id="onetidRichTextCompatible" name="RichText" title="Rich text (Bold, italics, text alignment, hyperlinks)" type="radio" value="COMPATIBLE" />
<label for="onetidRichTextCompatible">Rich text (Bold, italics, text alignment, hyperlinks)</label>
<input id="onetidRichTextFullHtml" name="RichText" title="Enhanced rich text (Rich text with pictures, tables, and hyperlinks)" type="radio" value="FullHtml" />
<label for="onetidRichTextFullHtml">Enhanced rich text (Rich text with pictures, tables, and hyperlinks)</label>
Maree N Percival
Maybe you are looking for
-
How can I open a word document in C++ with a CNiWordApplication object?
Hello, For an application, i need to open a word document using VisualC++ and CNiWord classes (CNiWordApplication, CNiWordDocument...). I successed to create a new CNiWordDocument with the CNiWordApplication CreateDocument() function. But when using
-
IPhone 4S 5.0.1 upgrade to 6.1.3 by on air. Is it possible?
Good day! Exuse me for my fluent English-I am from Russia)) I have Bought a new iphone 4s 64 GB recently. It has 5.0.1 firmware. Today it offered me to update on air to 6.1.3. (it's strange,because ios 7 is actually now) Can I do it or my iphone will
-
Batch save FIRST page only of PDF as JPEG??
Ok, frustrating afternoon here in sunny England... I have a large number of PDF magazines, of varying lengths. I would like to Open JUST the first page of the PDF (ie the cover) as an image Flatten it Save it as a JPEG Which sounds fairly simple. I c
-
MD04 - not getting updated, PR to PO conversion
Hi, We converted PR to PO in MD04 for whole quantity, ideally PR line should get replaced by PO line. 1. But PR line still remain in MD04 screen, PO line is added to MD04 screen 2. Am able to create more PO's for the same PR 3. PR lines goes off, if
-
Hi everybody, i've got the nokia 6080 phone and usb irda adapter and i am trying connect the phone to my pc, so that i can sync my contacts, but when i lay the phone near the adapter i have the message from pc suite: "PC Suite does not recognise the