Compare string in different line in text file
I am new to java and I need a simple example to compare string in file text by for loop
file.txt:
A78802 D06VAIS060253113 WKNEUP751346577450
A77802 D06VAIS060253113 WKNEUP751346577450
A76802 D06VAIS060253925 WKNEUP751346577450
A78802 D06VAIS075253698 WKNEGE226375082796
A73802 D06VAIS116253222 WKNEFB227345305299
dataString = TextIO.getln();
A=dataString.substring(25,42);
B=dataString.substring(195,203);
C=dataString.substring(171,186);
I WANT COPMPARE IN LINE 1 POSITION 20 TO LINE 2 POSITION 20 BY LOOPS ALL THE LINE IN TEXT FILE
what have you tried so far?
Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
// your code block goes here.
[/code]
Similar Messages
-
Compare two string in different line in textarea
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextCounterPanel extends JPanel {
private JTextArea textInput;
private JLabel lineCountLabel;
public TextCounterPanel() {
setBackground(Color.DARK_GRAY);
textInput = new JTextArea();
textInput.setBackground(Color.WHITE);
JPanel south = new JPanel();
south.setBackground(Color.DARK_GRAY);
south.setLayout( new GridLayout(4,1,2,2) );
JButton countButton = new JButton("Process the Text");
countButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
processInput();
south.add(countButton);
lineCountLabel = new JLabel(" Number of lines:");
lineCountLabel.setBackground(Color.WHITE);
lineCountLabel.setForeground(Color.BLUE);
lineCountLabel.setOpaque(true);
south.add(lineCountLabel);
setLayout( new BorderLayout(2,2) );
setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
JScrollPane scroller = new JScrollPane( textInput );
add(scroller, BorderLayout.CENTER);
add(south, BorderLayout.SOUTH);
public void processInput() {
String text,vin; // The user's input from the text area.
text = textInput.getText();
vin =text.substring(25,42);
lineCountLabel.setText(" vin: " + vin);
} // end class TextCounterPanel
How can I compare two string in different line in text areaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextCounterPanel extends JPanel {
private JTextArea textInput;
private JLabel lineCountLabel;
public TextCounterPanel() {
setBackground(Color.DARK_GRAY);
textInput = new JTextArea();
textInput.setBackground(Color.WHITE);
JPanel south = new JPanel();
south.setBackground(Color.DARK_GRAY);
south.setLayout( new GridLayout(4,1,2,2) );
JButton countButton = new JButton("Process the Text");
countButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
processInput();
south.add(countButton);
lineCountLabel = new JLabel(" Number of lines:");
lineCountLabel.setBackground(Color.WHITE);
lineCountLabel.setForeground(Color.BLUE);
lineCountLabel.setOpaque(true);
south.add(lineCountLabel);
setLayout( new BorderLayout(2,2) );
setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
JScrollPane scroller = new JScrollPane( textInput );
add(scroller, BorderLayout.CENTER);
add(south, BorderLayout.SOUTH);
public void processInput() {
String text,vin; // The user's input from the text area.
text = textInput.getText();
vin =text.substring(25,42);
lineCountLabel.setText(" vin: " + vin);
} // end class TextCounterPanel -
Read lines from text file to java prog
how can I read lines from input file to java prog ?
I need to read from input text file, line after line
10x !If you search in THIS forum with e.g. read lines from file, you will find answers like this one:
Hi ! This is the answer for your query. This program prints as the output itself reading line by line.......
import java.io.*;
public class readfromfile
public static void main(String a[])
if you search in THIS forum, with e.g. read lines from text file
try{
BufferedReader br = new BufferedReader(new FileReader(new File("readfromfile.java")));
while(br.readLine() != null)
System.out.println(" line read :"+br.readLine());
}catch(Exception e)
e.printStackTrace();
} -
How copy just line in text file with cat? (SOLVED)
Hi.
How i make to copy just only line in text file with cat?
For example:
[:0.0]
file=/home/Arch/./.wallpaper.png
mode=0
bgcolor=# 0 0 0
I want copy just "/home/Arch/./.wallpaper.png" part.
Actually i want create a shortcut for last wallpaper set from Nitroget, then i put this in SLim background.
Recently i use hsetroot for wallpaper (~/.wallpaper.png) and i create a shortcut in /usr/share/slim/theme/MYTHEME whith ln -s ~/.wallpaper.png /usr/share/slim/theme/MYTHEME/background.png.
I want make a same with Nitrogen.
I now this looks like crazy, but...
Sorry my English.
Last edited by kramerxiita (2008-06-04 16:50:48)moljac024 wrote:
kramerxiita wrote:
moljac024 wrote:How can you make SliM change the background ? You link the theme background to another file ?
Yes. In theme directory i put background.png shortcut for my wallpaper. So, when a change wallpaper, slim background change too.
Example:
ln -s mywallpaper.png /usr/share/slim/themes/default/background.png
So, Slim background always is my wallpaper.
So the wallpaper has to be a *.png ?
No, jpg is possible. But when you create a symbolic link, remember put the extension too. If change png to jpg, change a symbolic link extension.
But, remember if slim theme directory have background.png and background.jpg, Slim always choice .png. So, put only one this. -
How to write empty line in text file
hey
i want to insert one empty line in text file.
how to write this.
i declared
data: emptyrec(240) type c value space,
and used
TRANSFER emptyrec to e_file.
but its not inserting empty line in the record.
is there any special way have to do.
ambichan.hai anand,
I am posting the code snippet.
i have commented that transfer line in '----
' like this
pls refer below.
ambichan
DATA: PAGENO(4) TYPE N VALUE 1,
DATAKBN(2) TYPE N VALUE 1,
SUBNO(3) TYPE N VALUE 1,
VPAGENO(4) TYPE C,
VDATAKBN(2) TYPE C,
VSUBNO(3) TYPE C,
VREC(255) TYPE C,
VRECORD(255) TYPE C,
EMPTYREC(255) TYPE C VALUE SPACE,
VCODE(10) TYPE C,
VNAME2(35) TYPE C,
VPAYDAT(10) TYPE C,
VSGTXT(60) TYPE C VALUE SPACE,
VSGTXT1(10) TYPE C,
VKINGAKU(15) TYPE C VALUE SPACE,
VBIKKO(30) TYPE C VALUE SPACE,
VBELNR(10) TYPE C VALUE SPACE,
VDMBTR(15) TYPE C,
VGLT0-KSLVT(15) TYPE C,
VGLT0-TSL01(15) TYPE C,
VGLT0-TSL02(15) TYPE C,
VGLT0-TSL03(15) TYPE C,
VGLT0-TSL04(15) TYPE C,
VGLT0-TSL05(15) TYPE C,
VKIN(15) TYPE C,
VTEGA(15) TYPE C.
FORM FRM_OUTPUT_DATA.
SORT ITAB_OUTPUT_SUMMARY BY LIFNR DTYPE.
SORT ITAB_OUTPUT_ITEMS BY LIFNR DTYPE BELNR.
IF P_DISP = 'X'."checkボクスを選ぶ場合、ファイル作成処理へ行く
OPEN DATASET E_FILE FOR OUTPUT IN TEXT MODE.
IF SY-SUBRC <> 0.
WRITE: 'error',SY-SUBRC.
EXIT.
ENDIF.
LOOP AT ITAB_LIFNR.
PERFORM LISTDATA.
PAGENO = PAGENO + 1.
SUBNO = 1.
ENDLOOP.
CLOSE DATASET E_FILE."ファイルクローズ
ENDFORM. " End of frm_output_data
FORM LISTDATA.
DATA:
WK_PAY_AMOUNT LIKE BSEG-DMBTR, " 純支払額算出用
VWK_PAY_AMOUNT(15) TYPE C,
GLT0-TSL05_VAL LIKE GLT0-TSL05.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 1.
BSIK-DMBTR = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
GLT0-TSL01 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 2. " 区分:2
GLT0-TSL02 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 3. " 区分:3
GLT0-TSL03 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 4. " 区分:4
GLT0-TSL04 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 5. " 区分:5
GLT0-TSL05 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
glt0-tsl05 = glt0-tsl05 + glt0-tsl04.
WK_PAY_AMOUNT = GLT0-TSL05 + GLT0-TSL04.
CHECK WK_SUBRC = 0.
BSEG-KOART = ' '. 情報不要
CLEAR: BSEG-SGTXT, BSEG-DMBTR, TGSBT-GTEXT, BKPF-BELNR.
BSEG-KOART = 'Y'. " フラグ:ヘッダに相殺額を出力
CLEAR: BSAK-DMBTR.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 6. " 区分:6
BSAK-DMBTR = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
WK_PAY_AMOUNT = WK_PAY_AMOUNT - BSAK-DMBTR.
WRITE : / PAGENO,
SUBNO,
DATAKBN,
ITAB_LIFNR-LIFNR,
ITAB_LIFNR-NAME2(25),
P_PAY_T,
GLT0-TSL01,
GLT0-TSL02,
GLT0-TSL03,
GLT0-TSL04,
GLT0-TSL05.
VPAGENO = PAGENO.
VSUBNO = SUBNO.
DATAKBN = 1.
VDATAKBN = DATAKBN.
VCODE = ITAB_LIFNR-LIFNR.
VNAME2 = ITAB_LIFNR-NAME2.
VPAYDAT = P_PAY_T.
VGLT0-TSL01 = GLT0-TSL01.
VGLT0-TSL02 = GLT0-TSL02.
VGLT0-TSL03 = GLT0-TSL03.
VGLT0-TSL04 = GLT0-TSL04.
VGLT0-TSL05 = GLT0-TSL05.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT VKINGAKU
VBIKKO VBELNR VGLT0-TSL01 VGLT0-TSL02 VGLT0-TSL03
VGLT0-TSL04 VGLT0-TSL05 INTO VREC SEPARATED BY ','.
CLEAR: BSAK-DMBTR, BSID-DMBTR, BSAD-DMBTR, BSEG-DMBTR, BSIK-DMBTR,
WK_10 , WK_11 , GLT0-TSL05.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 7. " 区分:7
BSID-DMBTR = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
WK_PAY_AMOUNT = WK_PAY_AMOUNT - BSID-DMBTR.
郵送料の出力処理
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 8. " 区分:8
BSAD-DMBTR = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
WK_PAY_AMOUNT = WK_PAY_AMOUNT - BSAD-DMBTR.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 9. " 区分:9
BSEG-DMBTR = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
WK_PAY_AMOUNT = WK_PAY_AMOUNT - BSEG-DMBTR.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 10.
WK_10 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
READ TABLE ITAB_OUTPUT_SUMMARY
WITH KEY LIFNR = ITAB_LIFNR-LIFNR DTYPE = 11.
WK_11 = ITAB_OUTPUT_SUMMARY-DMBTR * WK_RATIO.
GLT0-TSL05 = WK_PAY_AMOUNT - WK_10 - WK_11.
WK_PAY_AMOUNT = WK_PAY_AMOUNT - GLT0-TSL05.
VWK_PAY_AMOUNT = WK_PAY_AMOUNT.
VKIN = WK_10.
VTEGA = WK_11.
CONCATENATE VREC VWK_PAY_AMOUNT VKIN VTEGA INTO
VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
WRITE :
VWK_PAY_AMOUNT,
WK_10,
WK_11.
WRITE:/.
BSEG-KOART = 'X'. " フラグ:請求金額を出力
LOOP AT ITAB_OUTPUT_ITEMS WHERE LIFNR = ITAB_LIFNR-LIFNR
AND DTYPE = 5. " 区分:5
BSEG-SGTXT = ITAB_OUTPUT_ITEMS-SGTXT. " 明細テキスト
GLT0-KSLVT = ITAB_OUTPUT_ITEMS-DMBTR * WK_RATIO. " 金額
TGSBT-GTEXT = ITAB_OUTPUT_ITEMS-GTEXT. BKPF-BELNR = ITAB_OUTPUT_ITEMS-BELNR.
SUBNO = SUBNO + 1.
VSUBNO = SUBNO.
DATAKBN = 2.
VDATAKBN = DATAKBN.
VGLT0-KSLVT = GLT0-KSLVT.
VBIKKO = TGSBT-GTEXT.
VBELNR = BKPF-BELNR.
VSGTXT1 ='請求金額:'.
CLEAR VRECORD.
CONCATENATE VSGTXT1 BSEG-SGTXT INTO VSGTXT.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT
VGLT0-KSLVT VBIKKO VBELNR INTO VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
WRITE :/ VPAGENO,VSUBNO,VDATAKBN,'請求金額:', VSGTXT, VGLT0-KSLVT,
VBIKKO,VBELNR.
ENDLOOP.
CLEAR: BSEG-SGTXT,GLT0-KSLVT,BKPF-BELNR.
LOOP AT ITAB_OUTPUT_ITEMS WHERE LIFNR = ITAB_LIFNR-LIFNR
AND DTYPE = 6. " 区分:6
BSEG-SGTXT = ITAB_OUTPUT_ITEMS-SGTXT. " 明細テキスト
IF ITAB_OUTPUT_ITEMS-SHKZG = CNS_CREDIT. " 金額
GLT0-KSLVT = ITAB_OUTPUT_ITEMS-DMBTR * WK_RATIO.
ELSEIF ITAB_OUTPUT_ITEMS-SHKZG = CNS_DEBIT.
GLT0-KSLVT = ITAB_OUTPUT_ITEMS-DMBTR * WK_RATIO * -1.
ENDIF.
TGSBT-GTEXT = ITAB_OUTPUT_ITEMS-GTEXT. " 事業領域テキスト
BKPF-BELNR = ITAB_OUTPUT_ITEMS-BELNR. " 伝票番号
SUBNO = SUBNO + 1.
VSUBNO = SUBNO.
DATAKBN = 3.
VDATAKBN = DATAKBN.
VGLT0-KSLVT = GLT0-KSLVT.
VBIKKO = TGSBT-GTEXT.
VBELNR = BKPF-BELNR.
VSGTXT1 ='相殺金額:'.
CLEAR VRECORD.
CONCATENATE VSGTXT1 BSEG-SGTXT INTO VSGTXT.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT
VGLT0-KSLVT VBIKKO VBELNR INTO VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
concatenate vpageno vsubno vdatakbn
WRITE :/ PAGENO,SUBNO,DATAKBN,'相殺金額',BSEG-SGTXT, GLT0-KSLVT,
TGSBT-GTEXT, BKPF-BELNR.
ENDLOOP.
CLEAR VRECORD.
*Insert empty line.
TRANSFER EMPTYREC TO E_FILE.
DATAKBN = 3.
VDATAKBN = DATAKBN.
SUBNO = SUBNO + 1.
VSUBNO = SUBNO.
VSGTXT ='源泉金額'.
VDMBTR = BSID-DMBTR.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT
VDMBTR INTO VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
WRITE :/ PAGENO, SUBNO,DATAKBN, ITAB_LIFNR-LIFNR,ITAB_LIFNR-NAME2,
P_PAY_T,'源泉金額', BSID-DMBTR.
CLEAR: VDMBTR, VSGTXT, VRECORD.
SUBNO = SUBNO + 1.
VSUBNO = SUBNO.
VSGTXT = '郵送料'.
VDMBTR = BSAD-DMBTR.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT
VDMBTR INTO VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
WRITE :/ PAGENO, SUBNO,DATAKBN,ITAB_LIFNR-LIFNR,ITAB_LIFNR-NAME2,
P_PAY_T,'郵送料', BSAD-DMBTR.
CLEAR: VDMBTR, VSGTXT, VRECORD.
SUBNO = SUBNO + 1.
VSUBNO = SUBNO.
VSGTXT = '振込み手数料'.
VDMBTR = BSEG-DMBTR.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT
VDMBTR INTO VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
CLEAR: VDMBTR, VSGTXT, VRECORD.
WRITE :/ PAGENO,SUBNO,DATAKBN,ITAB_LIFNR-LIFNR,ITAB_LIFNR-NAME2,
P_PAY_T,'振込み手数料',BSEG-DMBTR.
*その他の支払いの処理
SUBNO = SUBNO + 1.
VSUBNO = SUBNO.
VSGTXT = 'その他の支払い'.
VDMBTR = GLT0-TSL05.
CONCATENATE VPAGENO VSUBNO VDATAKBN VCODE VNAME2 VPAYDAT VSGTXT
VDMBTR INTO VRECORD SEPARATED BY ','.
TRANSFER VRECORD TO E_FILE.
WRITE :/ PAGENO,SUBNO,DATAKBN,ITAB_LIFNR-LIFNR,ITAB_LIFNR-NAME2,
P_PAY_T, 'その他の支払い',GLT0-TSL05.
glt0-tsl05.
ULINE.
CLEAR: VREC, VRECORD,VCODE,VNAME2,VPAYDAT,VSGTXT,VSGTXT1,VKINGAKU.
CLEAR: VBIKKO,VBELNR,VDMBTR,VGLT0-KSLVT,VGLT0-TSL01,VGLT0-TSL02.
CLEAR: VGLT0-TSL03,VGLT0-TSL04,VGLT0-TSL05,VKIN,VTEGA,VWK_PAY_AMOUNT.
ENDFORM. -
Find and edit specific line in text file?
Hello I want to read a text file that could look in some different ways since the user choose file from a list. I then want to igonre all the lines that begin with a special character, for example %. I then want to find all the lines "words" that begin with TRY for example and put those "words" in a string or array. If there is one line that contains TRY100 and anoter line that contains TRY200 I want to find those words and display them. How do i do this?
First you read the entire file. Use the Read Text File. Right-click on it and select the option to Read Lines. The the count to read to -1 (read all). You will now have an array of strings, one item for each line of your file.
Now you need to play the filter game. I recommend using FOR loops with Autoindexing tunnels. Assuming you are using 2012 or later, have the output autoindexing tunnels use the conditional tunnel.
Give this a try and see where you can go. Post back with what you have tried and tell us where you are stuck.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
Skipping Blank Lines in text File
I am working on an assignment in which i have to read from a text file and store the strings individually. The problem i have is that the text file has blank line between each set of strings. So i figured to use "fin.nextLine();" to skip that blank line and continue with storing the values. but i get
"Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at processmsg.ProcessMessages.choice1(ProcessMessages.java:68)
at processmsg.ProcessMessages.main(ProcessMessages.java:25)"
which is where the fin.nexLine() is at. How can i just skip that blank line?
System.out.println("Please enter the file location");
Scanner stdin = new Scanner(System.in);
String fileName = stdin.nextLine();
// read the information from the file
try {
Scanner fin = new Scanner(new File(fileName));
String tSendName = fin.nextLine();
while(tSendName != null)
String tRecieveName = fin.nextLine();
String tPhoneNumber = fin.nextLine();
String tDate = fin.nextLine();
String tTime = fin.nextLine();
String tStatus = fin.nextLine();
String tMessage = fin.nextLine();
PhoneMessage phonemessage = new PhoneMessage(tSendName, tRecieveName,
tPhoneNumber, tDate, tTime, tStatus, tMessage);
fin.nextLine();
tSendName = fin.nextLine();don't know if you want the whole code, the whole code is kind of large and spread out over 3 different classes. and yes the text file is standard
sender
reciever
phone number
date
time
status
message
sender
reciever
phone number
date
time
status
message
sender
reciever
phone number
date
time
status
message
private static void choice()
// scan the file location from the user
System.out.println("Please enter the file location");
Scanner stdin = new Scanner(System.in);
String fileName = stdin.nextLine();
// read the information from the file
try {
Scanner fin = new Scanner(new File(fileName));
String tSendName = fin.nextLine();
while(tSendName != null)
String tRecieveName = fin.next();
String tPhoneNumber = fin.next();
String tDate = fin.nextLine();
String tTime = fin.nextLine();
String tStatus = fin.nextLine();
String tMessage = fin.nextLine();
PhoneMessage phonemessage = new PhoneMessage(tSendName, tRecieveName,
tPhoneNumber, tDate, tTime, tStatus, tMessage);
// skip blank line between entries
fin.nextLine();
// test date string for correct format
int month = Integer.parseInt(tDate.substring(0,2));
int day = Integer.parseInt(tDate.substring(3,5));
int year = Integer.parseInt(tDate.substring(6,10));
// test time string for correct format
int hour = Integer.parseInt(tTime.substring(0,2));
int minute = Integer.parseInt(tTime.substring(3,5));
int second = Integer.parseInt(tTime.substring(6,8));
tSendName = fin.nextLine();
msgList.add(phonemessage);
fin.close();
} catch (FileNotFoundException e) {
System.out.println("The file " + fileName + " was not found!");
} catch (java.lang.NumberFormatException e) {
System.out.println("The date and/or time is not of the correct format");
} -
How Can I replace line in text file
I have a text file like following format
1
bvhhk
g1
2
bvgjvh
g1
3
mmm,mvb
g2
I want to replace 2 nd line to " prasad" and after replacing it should be following format
1
prasad
g1
2
bvgjvh
g1
3
mmm,mvb
g2
I try above change using following code segment and it is not work.
static void modifyEmployeeDetails(String file_name){
try{
InputStreamReader reader= new InputStreamReader(System.in);
BufferedReader buff=new BufferedReader(reader);
FileReader read=new FileReader(file_name);
BufferedReader buffer=new BufferedReader(read);
FileWriter w=new FileWriter(file_name,true);
PrintWriter write = new PrintWriter(w);
System.out.print("Employee No : ");
String No=buff.readLine();
boolean eof = false;
while (!eof) {
String tep=buffer.readLine();
if(tep.equals(No)){
eof = true;
System.out.print("Name : ");
temp=buff.readLine();
System.out.println("No");
write.println(temp);
System.out.print("Group No : ");
temp=buff.readLine();
write.println(temp);
}catch(Exception e){
System.out.println(e);
Please correct If it is wrong and help me as soon as possible
Thank you...............hi,
I have a different approach of the solution to your problem.
suppose you have entries in your file without any extra line feed between each two entries.
the following program entirely reads your data into a bean list, changes a specific bean attribute and writes it to your data source.
(you should adapt it to your needs)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileReplace {
public List<MyBean> readFile(BufferedReader in) throws IOException{
String line;
List<MyBean> beanList = new ArrayList<MyBean>();
MyBean bean = null;
int i=0;
while((line=in.readLine())!=null){
if(line.trim().equals("***")){
beanList.add(bean);
i = 0;
}else{
switch (i) {
case 0:
bean = new MyBean();
bean.setAttribute1(line);
i++;
break;
case 1:
bean.setAttribute2(line);
i++;
break;
case 2:
bean.setAttribute3(line);
i++;
break;
default:
break;
return beanList;
public void writeToFile(List<MyBean> beanList, String outputFilePath) throws IOException{
FileWriter out = new FileWriter(outputFilePath);
for (int i = 0; i < beanList.size(); i++) {
out.write(beanList.get(i).toString());
out.flush();
out.close();
public void test(){
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String filePath = "D:/file.txt";
try {
BufferedReader in = new BufferedReader(new FileReader(filePath));
//read data
List<MyBean> beanList = readFile(in);
// edit a bean attribute
beanList.get(0).setAttribute2("prasad");
//write beans back to file
writeToFile(beanList, filePath);
} catch (FileNotFoundException e) {
e.printStackTrace(); //handle appropriately this exception
} catch (IOException e) {
e.printStackTrace();//handle appropriately this exception
}catch (Exception e) {
e.printStackTrace();//handle appropriately this exception
class MyBean{
String attribute1;
String attribute2;
String attribute3;
public final static int ATTRS_NUMBER = 3;
public String getAttribute1() {
return attribute1;
public void setAttribute1(String attribute1) {
this.attribute1 = attribute1;
public String getAttribute2() {
return attribute2;
public void setAttribute2(String attribute2) {
this.attribute2 = attribute2;
public String getAttribute3() {
return attribute3;
public void setAttribute3(String attribute3) {
this.attribute3 = attribute3;
@Override
public String toString() {
return attribute1+"\n"+attribute2+"\n"+attribute3+"\n***\n";
public static void main(String[] args) {
FileReplace instance = new FileReplace();
instance.test();
}hope it helps -
Folks:
What's the best way to count the number of lines in a text file?
thanks,
KevinYou can also skip the open/create, you'll still get a file dialog. I guess EOL conversion is also not needed.
So the most minumalistic code is as follows.
Has anyone done any benchmarks? Somehow I have the feeling that temporarily creating that big array of strings might not be the most efficient compared to reading all as one string and counting linefeeds. Who knows...? How big are your files?
Message Edited by altenbach on 09-29-2006 04:03 PM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
CountLines.png 1 KB -
Reading strings and integers from a text file
I want to read the contents of a text file and print them to screen, but am having problems reading integers. The file contains employee's personal info and basically looks like this:
Warren Laing
32 //age, data type is int
M //gender, data type is String
Sharon Smith
44
F
Here's what I've done so far. The method should continue reading the file until there's no lines left. When I call it from main, I get a numberFormatException error. I'm not sure why because the data types of the set and get methods are correct, the right packages have been imported, and I'm sure I've used Integer.parseInt() correctly (if not, pls let me know). Can anyone suggest why I'm getting errors, or where my code is going wrong?
many thanks
Chris
public void readFile() throws IOException{
BufferedReader read = new BufferedReader(new FileReader("personal.txt"));
int age = 0;
String input = "";
input = read.readLine();
while (input != null){
setName(input);
age = Integer.parseInt(input);
setAge(age);
input = read.readLine();
setGender(input);
System.out.println("Name: " + getName() + " Age: " + getAge() + " Gender: " + getGender());
read.close();To answer your question - I'm teaching myself java and I haven't covered enumeration classes yet.
With the setGender("Q") scenario, the data in the text file has already been validated by other methods before being written to the file. Anyway I worked out my problems were caused by "input = read.readLine()" being in the wrong places. The code below works fine though I've left out the set and get methods for the time being.
Chris
public static void readFile()throws IOException{
String name = "";
String gender = "";
int age = 0;
BufferedReader read = new BufferedReader(new FileReader("myfile.txt"));
String input = read.readLine();
while(input != null){
name = input;
input = read.readLine();
gender = input;
input = read.readLine();
age = Integer.parseInt(input);
input = read.readLine();
System.out.println("Name: " + name + " Gender: " + gender + " Age: " + age);
read.close(); -
Appending to new line in text file
I am trying to append text to a new line to a file. I set the append parameter to true and I try to output the new line character after I write the string to the file. However it is still appending the next string to the end of the first rather than in the line below. My code is below. Can someone please help me?
Thanks
public static boolean WriteToFile(String nameOfFile,
String contents)
FileWriter myFileWriter = null;
try
System.out.println("Attempting to write text to = " + nameOfFile);
myFileWriter = new FileWriter(nameOfFile,true);
myFileWriter.write(contents);
myFileWriter.write('\n');
myFileWriter.close();
return true;
catch (Exception e)
System.out.println("EXCEPTION thrown ");
return false;
}I am trying to append text to a new line to a file.
I set the append parameter to true and I try to
o output the new line character after I write the
string to the file. However it is still appending the
next string to the end of the first rather than in
the line below. My code is below. Can someone please
help me?
Thanks
public static boolean WriteToFile(String nameOfFile,
String
String
String contents)
FileWriter myFileWriter = null;
try
System.out.println("Attempting to write
ting to write text to = " + nameOfFile);
myFileWriter = new
eWriter = new FileWriter(nameOfFile,true);
myFileWriter.write('\n');
myFileWriter.write(contents); myFileWriter.close();
return true;
catch (Exception e)
System.out.println("EXCEPTION thrown ");
return false;
try the change what i have made in bold -
Removing first line in text file... Memory and HD concern
Hello all,
I want to remove the first line of a text file. This is easy... One way
to do it, is to find the first "end of line" caracter, strip the string
and re-write the sting in file with the "strip to sreadsheet" VI.
Since the file can be quite large (about 120000 lines), is this a good
way to do it. Will it re-write all the line or just moving the "begin
of file" pointer to the second line? If it re-write the whole file,
this option is not very good since I could have to do this operation
quite often. (I want the file to be a kind of circular buffer / backup).
What do you think is the best way to do this?
Thanks!
VincentI think you would have to read in all the data and write it to a new file, you could either keep the data in RAM or simply write to another file then delete the original, and then rename the temp one. So obviously that is a lot of data and memory.
My main question is are you trying to use a text file as a circular buffer? If so can you tell us more about the data, ie is it strings of a constant length? Does a user ever need to read the file or could we head binary?
A solution would be to truly make the file a binary file, so you could actually seek through the file easier, and maybe make the first data chunk the location of the most recent write. The obvious danger is then writing over existing data. This solution is still risky because of the data writes.
You may want to look at some of the other file formats like HWS which maintains a hierarchy of data for you so you can simply add and remove data from it. However, a user will not be able to easily read it. -
Hi -
Im using the FileWriter and BufferedWriter classes to output text into a .txt file.
The text I am writing is taken from another text file using the FileReader and BufferedReader classes.
The text is reading from the file, and will also output to the new text file, however it won't insert a new line, it only inserts an 'unprintable' character i.e. an empty square
My code is below - its only starting out so its farily simple at the moment, just reading from one file and outputting to another.
Is there a way i can get the actual new line/carriage return inserted instead of the empty square. (im running Windows XP)
Thanks in advance
import java.io.*;
public class Pad {
private String inputPath;
private String outputPath;
/** Creates a new instance of Pad */
public Pad() {
inputPath = "C:\\OUTBOUND.TXT";
outputPath = "C:\\04'06.txt";
* @param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
System.out.println("PAD File");
//Read PAD File
Pad p = new Pad();
p.readPADFile(p.inputPath, p.outputPath);
public void readPADFile(String inputPath, String outputPath)
inputPath = this.inputPath;
outputPath = this.outputPath;
//System.out.println(inputPath);
int recordCount = 0;
String record = null;
try
FileReader fr = new FileReader(inputPath);
FileWriter fw = new FileWriter(outputPath);
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
record = new String();
while((record = br.readLine())!=null)
recordCount++;
//System.out.println(recordCount + ": " + record);
bw.write(record + "\n");
bw.close();
br.close();
fw.close();
fr.close();
}catch(IOException e)
System.out.println("IOException Error");
e.printStackTrace();
System.out.println(e.toString());
}I assume by using the
System.getProperty("line.separator") that this will
work independent of platform.Yes. And using bw.println() instead of bw.print() will already do it for you. So all you need to change in your program are two letters. -
How to read long line from text file
Hi,
I just faced problem when reading a big text file.
BufferedReader br = new BufferedReader(new FileReader("D:\\afile.txt"));
String str;
int i;
while ((str = br.readLine())!=null)
i++;
//do some work here...
...This code throws exception:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceSo I thought file line is very long. When I opened it in FAR it only displays no more than 4096 characters as a line.
Help me to read a text file that's line is very long?try,
$ java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xrunhprof[:help]|[:<option>=<value>, ...]
perform JVMPI heap, cpu, or monitor profiling
-Xdebug enable remote debugging
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
The -X options are non-standard and subject to change without notice. -
How to write a string a stringbuffer to a text file or read a file?
I need create a text file if the file is not exist, if exist, I have to append a string or stringbuffer to the file. Basically I am using java server page for our web application. I need send user input into a text file. I am uploading my JSP into a server, and run JSP from server. I wonder if I want to create a file, where this file goes, and how can I specify the path of the file?
I used: BufferedReader br = new BufferedReader( new FileReader("report.txt"));
The file report.txt could not be found.
Please help me, thank you so muchTry
File file = new File("report.txt");
out.println("File name: "+file.getAbsolutePath());in your jsp page, then you will see where it would be placed it you created it.
You can specify the full path like this:
File wFile = new File("c:\\temp\\report.txt"); // for windows
File uFile = new File("/tmp/report.txt"); // for unix/linux
// or
File file = new File(myPath, "report.txt"); // where myPath is the path where you want to place report.txt.You can either use a File object or String object in the FileReader constructor..
If you just want to know if the file exits, then use a file object and call exists() on it, returns true if the file already exist. If you want to create the file if it doesn't exit and append a string, then you don't need to check if it exist first. Just do it like this:
PrintStream ps = new PrintStream(new FileOutputStream("report.txt", true), true);
// again you could use a file object instead of a string with the file name
ps.println("Add this line");
ps.close();If the file doesn't exist, it will create it for you. The second argument in FileOutputStream means "append", and the second argument in PrintStream means "autoflush" every time you use the println methods (or add a newline '\n').
Maybe you are looking for
-
Risks associated with database refresh.
Hi experts, I need to clarify a doubt .I have a cloned SAP BW system (from another system i.e SAn to SAN copy)and then after few months after the first clone I need to refresh the database(Oracle 10 G).The reason being I will have some changes in da
-
Hi Experts, What we are trying to do is to change prices for 106 products for 26 plants. So when we try to record LSMW it is giving materials and plants as index. Like MATNR_01 MATNR_02 and NEWVALPR_01NEWVALPR_02. How will we make the file based on
-
How to Configure POWL in SRM 7 Shopping Cart
Hi, Can i know how to configure POWL for SRM7 Shopping Cart with regards, Kawrthik.
-
Error on transaction SFP: FPUIFB043
Hello masters: I have a problem when I try to show the layout tab in transaction SFP. The error message is the next: "Error occurred in communication with layout editor", Message number FPUIFB043. Does anybody know what I need to do? thank you.
-
Stroke Width Relative to Resizing
When I have an oject that has a stroke outline of say, 10 pt., and I resize the object, everything resizes except for the stroke width which remains at 10pt. Is there a way to fix the stroke width so that it resizes with the other attributes of the o