Some times we may need to read test data from text file. We can achieve this using simple Java snippet. following code will help you to address this
import java.io.*;
public class ReadTextFile {
public static void main(String[] args){
String readFile ="D://test.txt";
String writeFile ="D://test1.txt";
//reading contents from a text file
try{
InputStream ips=new FileInputStream(readFile);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
br.readLine();
String[] n = null;
while ((line =br.readLine())!=null){
n = line.split(",");
for(int i = 0; i < n.length; i++)
{
System.out.print(n[i]);
}
System.out.println("\n");
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
//writing to a text file
try {
FileWriter fw = new FileWriter (writeFile);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter fileOut = new PrintWriter (bw);
fileOut.println ("\n1. Writing Content to text file");
fileOut.println ("\n2. Writing content to text file");
fileOut.close();
}
catch (Exception e){
System.out.println(e.toString());
}
}
}
Inupt file contents(test.txt):
First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name
Password:, Password
Email:, email
First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name1
Password:, Password1
Email:, email1
import java.io.*;
public class ReadTextFile {
public static void main(String[] args){
String readFile ="D://test.txt";
String writeFile ="D://test1.txt";
//reading contents from a text file
try{
InputStream ips=new FileInputStream(readFile);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
br.readLine();
String[] n = null;
while ((line =br.readLine())!=null){
n = line.split(",");
for(int i = 0; i < n.length; i++)
{
System.out.print(n[i]);
}
System.out.println("\n");
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
//writing to a text file
try {
FileWriter fw = new FileWriter (writeFile);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter fileOut = new PrintWriter (bw);
fileOut.println ("\n1. Writing Content to text file");
fileOut.println ("\n2. Writing content to text file");
fileOut.close();
}
catch (Exception e){
System.out.println(e.toString());
}
}
}
Inupt file contents(test.txt):
First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name
Password:, Password
Email:, email
First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name1
Password:, Password1
Email:, email1