Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Readin a text file and cuttin the text

 
kristian
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this following code cuts the string test
"This is not easy " into equal length peaceslike this:
this
is n
ot e
asy
How do i have to change the code so that I can read the text from a file (for example "help.txt"),file can have several text lines and the result should be the same as above

String test=" This is not easy"; test=test.trim();
int spacefound=0;
String tmp="";
int l=test.indexOf(" ");
for(int i=0;i<test.length();i++){
char c=test.charAt(i);
if(c!=' ') tmp+=""+c;
if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
tmp+=""+c;
spacefound++; }
if(tmp.length()==l){
System.out.println(tmp);
tmp="";
spacefound=0;
} }
if(tmp.length()<l){
for(int i=0;i<=(l-tmp.length());i++) tmp+=""+' '; }
System.out.println(tmp);
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kristian
Welcome to the Java Ranch, we hope you’ll enjoy visiting as a regular however,
your name is not in keeping with our naming policy here at the ranch. Please re-register under an appropriate name as shown in the policy.
Thanks again and we hope to see you around the ranch!!
 
Alex Ku
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This will read one line at a time. You can do a while loop to get all the line. when the return value is null, it is end of file.
Ping
[ January 18, 2002: Message edited by: kawaii desu ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic