Read data from csv file using java in webdriver - selenium-webdriver

How to read data of each cell in Selenium WebDriver using Java?
I have tried with following code:
CSVReader reader = new CSVReader(new FileReader("D:/data1.csv"));
expectedLabels = reader.readNext();
FieldNames = reader.readNext();
FieldValues = reader.readNext();

File file = new File("D:/data.csv");
if(file.exists()){
System.out.println("File Exists");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufRdr.readLine()) != null){
StringTokenizer st = new StringTokenizer(line,",");
col=0;
while (st.hasMoreTokens()){
//Following stroing the data of csv
numbers[row][col] = st.nextToken();
col++;
}
System.out.println();
row++;
}
bufRdr.close();

reading csv files become very easy with OPENCSV jar file. I have used this jar file couple of time to read file.
We have predefined class called CSVReader, create an object and pass the csv file path
call readAll() method which will return the csv content in List
using Iterator, you can iterate all the values and use according to application
I have written article on this have a look it might help you.
http://learn-automation.com/how-to-read-csv-files-using-java/

I am not able to provider string type variable in FileReader() function , it shows error while passing filereader() method with parameter in buffer reader fn
code shown below:
String f1= (System.getProperty("User.dir") + "\\Module9TestNG\\src\\TestLogin.xlsx");
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String record;
String url= null;
while ((record = bufRdr.readLine()) != null)
{
String fields[] = record.split(",");
url= fields[0].toString();
}

private String Fpath ="D:\\CkycApps.csv";
String line;
File file = new File(Fpath);
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
while((line = bufRdr.readLine()) != null){
System.out.println(line);
String[] cell= line.split(",");
String FirstName=cell[0];
String MiddleName=cell[1];
}

Related

Importing 2 types of variables from text file

I am not very fluent, simple question: when i have text file like this:
Name number
Name2 number2
How do i import it to Arrays, that I can operate on both of these? Numbers and names are separated by space. I have seen guides just to one type of variable, but what if i have two of them?
In pseudocode
while not eof:
read name
do sth with name
read number
do sth with number
In Java
String line;
String[] row;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
while ((line = br.readLine()) != null) {
row = line.split("\\s+");
names.add(row[0]);
numbers.add(Integer.parseInt(row[1]));
}
} catch (IOException e) {}

Input Mismatch scanner.next(string pattern) from file

I'm having a problem while using a
Scanner file = new Scanner(filePath);
my file is organised as so
Question x.y
Answer1
Answer2
Answer3
Answer4
Hint: Hint to Question x.y Level z Genere t
I'm quite new to java and in all of this project I've used
.next(string pattern)
to return a string that includes the parrtern and arrives to the end of the line but i continue to get mismatch exceptions.. i don't really get what
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
defines as token and for this reason i don't know how to handle it..
my code is
public Question getQuestion(String filePath)
{
ArrayList questions = new ArrayList();
Scanner file = new Scanner(filePath);
String questionInFile = "Question";
while(file.hasNextLine())
questions.add(questionInFile+file.next(questionInFile));
Random rg = new Random();
String Q = (String)questions.get(rg.nextInt(10)+1);
file.close();
ArrayList<String> answer=getAnswers(filePath, Q);
String correctAnswer=answer.get(0);
return new Question(Q, answer, correctAnswer);
}
try adding
File filePath = new File(".txt");
before Scanner file

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

read a text file line by line

I need to read data from a text file line by line. Each line contains either a string or an integer. I want to use StreamReader to read line by line from the text file and StreamWriter to write it to a binary file. The "write to binary file" part will be easy. The "read from text file line by line" part is the part I need help with.
It's all built into StreamReader:
using (var sr = new StreamReader(myFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// line is the text line
}
}
In c# you can do something like this.
string loc = "idk/where/ever";
using(var sr = new StreamReader(loc))
using(var sw = new StreamWriter(loc+".tmp"))
{
string line;
while((line=sr.ReadLine())!=null)
{
sw.WriteLine(line);
//edit it however you want
}
}
File.Delete(loc);
File.Move(loc+".tmp",loc);

JavaMail and non-ASCII character in filenames

I can send attachments that have non-ascii filenames in JavaMail but I am not able to download them. I am getting java.io.FileNotFoundException specifically for those attachments whose file names contain non-ascii characters.
FYI: I am using something like messageBodyPart.setFileName(MimeUtility.encodeText(filename[i])) to encode the text and MimeUtility.decodeText(bodyPart.getFileName()) to decode the non-ascii file names
Is there a workaround for this?
EDIT
#Bill, here is part of my code that reads attachments. I have also added the properties.setProperty("mail.mime.decodeparameters", "true") and properties.setProperty("mail.mime.decodefilename", "true") properties in my code.
if (message[a].getContent() instanceof MimeMultipart) {
Multipart multipart = (Multipart) message[a].getContent();
for (int i = 0; i < multipart.getCount(); i++) {
bodyPart = multipart.getBodyPart(i);
disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT) || (disposition.equals(BodyPart.INLINE)))) {
DataHandler handler = bodyPart.getDataHandler();
String path = bodyPart.getFileName();
String[] str = path.split("/");
String fileName = str[str.length - 1];
String filePath = ReadConfigPropertiesFile.getPropertyValue("server.buildpath");
System.out.println(fileName);
File tempDir = new File(filePath + user);
if (!tempDir.exists()) {
tempDir.mkdir();
}
File saveFile = new File(tempDir + "/" + fileName);
int count = 0;
while (saveFile.exists()) {
count++;
saveFile = new File(tempDir + "/" + count + "_" + fileName);
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile));
byte[] buff = new byte[2048];
InputStream is = bodyPart.getInputStream();
int ret = 0;
while ((ret = is.read(buff)) > 0) {
bos.write(buff, 0, ret);
}
bos.close();
is.close();
//System.out.println(bodyPart.getContentType());
}else {
//display body (message) of the attachment;
//System.out.println(bodyPart.getContent().toString());
}
}
}
The above code raises the FileNotFoundException exception at BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile)) line and this is getting raised for the attachments whose file names are non-ascii characters (something like ሰላም.pdf). Every thing else works fine.
This answer taken from comment of #semytech (OP). It was hard to find it there, so I will add it as answer for more visibility. It helped me with hebrew filenames.
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(MimeUtility.encodeText(filename, "UTF-8", null));
You should never need to do the encoding or decoding yourself.
There are two sets of properties you can set to tell JavaMail to do the encoding/decoding for you:
mail.mime.encodefilename/mail.mime.decodefilename
mail.mime.encodeparameters/mail.mime.decodeparameters
See the javadocs for the javax.mail.internet package for details.
The first set uses a non-standard encoding technique, similar to what you're doing yourself. This works fine with some older mailers that use this technique.
The second set uses a MIME standard encoding technique. This version works with most modern mailers.
None of this explains why you're getting FileNotFoundException, but then you didn't provide enough detail to know what you're doing when you get the exception.

Resources