• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

how to read from a file ?  RSS feed

 
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i need to perform some string operations on strings contained inside a text file. So how does one read the strings from the text file into the program ?
eg say the text file contains names:
john mary edwin bill george rossane
i need to be able to read each of the above strings into my program and do say things with methods like startsWith(), endsWith() etc.
how do we read in the strings sequentially one after one.....
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Had a few problems with this myself.
This seems to work ok for me though.
import java.io.*;
public class rw_line
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("old.txt");//Open the files
File outputFile = new File("new.txt");
BufferedReader in = new BufferedReader(new FileReader(inputFile));
PrintStream out = new PrintStream(new FileOutputStream(outputFile));

String str;
while ((str = in.readLine()) != null)//While the end of the file has not been reached
{
out.println(str); //Print the line into the file
}
in.close();//Close the files
out.close();
}
}
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Check whether the code below solves ur problem.
code is:
--------
import java.io.*;
import java.util.*;
public class rw_line
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("Old.txt");
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String str = null, str1 = "";

while ((str = in.readLine()) != null)
{
str1 += str+" ";
}

in.close();

StringTokenizer tokenizer = new StringTokenizer(str1," ");

String token = null;

while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();

System.out.println("Each name is :"+token);
}
}
}
 
Everybody! Do the Funky Monkey! Like this tiny ad!
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!