Randomly read text from specific column in a file using Java - java

I would like to randomly select single name from column1 between Robert,Shawn,John.
Example The File has following names
Robert,Brian
Shawn,Bay
John,Paul
Any Help would be highly appreciated
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir")+path);
in = new BufferedReader(new InputStreamReader(objfile ));
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//trying to randomly select text from specific row in a property file
sendKeys(firstName,rand.nextInt((eachRecord[0]));
line = in.readLine();
}
}

This gets a random name from column 1 into the variable randomName:
final int column = 1;
final String path = "file.ext";
Random rand = new Random();
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
String randomName = lines.get(rand.nextInt(lines.size())).split(",")[column - 1];

FileReader fr = new FileReader(path_of_your_file);
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
ArrayList<String> nameList=new ArrayList<String>(); //keep each first column entry inside this list.
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st=new StringTokenizer(sCurrentLine, ",");
String name=st.nextToken();
nameList.add(name);
}
System.out.println(nameList.get((int)(Math.random()*nameList.size())));
//close file resources at finally block.

Related

read random word from CSV file java (wordle project)

how do I get this to read from a csv file and choose a random word from a list I have. I can get it to print the first few words but I want it to just choose one randomly. As you can tell Im very new to java.
String csvFile = "src/data/Book1.csv";
WordleWord[] arrays = new WordleWord[6];
FileReader fileReader = new FileReader(csvFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String nextLine = bufferedReader.readLine();
String[] strings1 = nextLine.split(",");
String randomWord = strings1[0];
String randomWord1 = strings1[0];
for (int i = 0; i < arrays.length; i++) {
nextLine = bufferedReader.readLine();
if (nextLine != null) {
String[] strings = nextLine.split(","); //split the string when commas occur
String word = strings[0];
arrays[i] = new WordleWord(word);
arrays[i] = new WordleWord(word);
String chosenRandomWord = Random(arrays[i]);
System.out.println(word);

How to read text file without the headline into ArrayList

I'm currently working on an assignment and I cannot find any clue to remove the headline from the text file and write the rest into an ArrayList. Can someone help me?
ID,Nama,GajiPokok,JmlAbsensi,JmlIzin
2,Peter,5000000,17,3
1,John,4500000,19,1
3,Linda,10000000,13,7
4,Lucy,7000000,20,0
Here is my code:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
try {
String line = in.readLine();
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
in.close();
} catch (IOException e){e.printStackTrace();}
If you want to ignore first line while reading the CSV file then you can simple skip processing of 1st line by calling in.readLine(); twice at the start as shown in below example:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
String line = in.readLine();
line = in.readLine(); //skip fist line and read second line
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
Using skip() method of JAVA 8 Streams:
try(BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"))) {
Stream<String> lines = in.lines();
List<Staff> staff = lines.skip(1).map(line -> {
Staff s = new Staff();
String data[] = line.split(",");
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setJmlhAbsensi(Integer.parseInt(data[3]));
s.setJmlhIzin(Integer.parseInt(data[4]));
return s;
}).collect(Collectors.toList());
System.out.println(staff);
}
You can declare the following line twice or initialize integer variable and skip the loop if its zero.
String line = in.readLine();
This solution works.
private void readTextFile(String fileName) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
Stream<String> stream = in.lines();
List<String> answer = stream.collect(Collectors.toList());
// For Pre-Java8
/*for (int i = 1; i < answer.size(); i++) {
System.out.println(answer.get(i));
}*/
// Split afterwards.
Stream<String> ans = answer.stream().filter(p -> !p.equals(answer.get(0)));
ans.forEach(x -> System.out.println(x));
}

Write values from multidimensional array to csv file in java

I wrote a small Java program that reads the data from CSV file and I have to save these values in 2 dimensional array. Now I need to write these values (not all information will be stored because the array contains many redundant data) from this array to a new CSV file. Can anyone help me with a code sample, I searched a lot but could not find an answer. My code is:
int row = 0;
int col = 0;
String[][] numbers=new String[24][24];
File file = new File("D:\\thesis\\sorted_file.csv");
if(file.exists())
{
System.out.println("file exist");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
String delims=",";
//read each line of text file
while((line = bufRdr.readLine()) != null )
{
StringTokenizer st = new StringTokenizer(line,delims);
col=0;
while (st.hasMoreTokens())
{
//get next token and store it in the array
numbers[row][col] = st.nextToken();
System.out.print("number["+row+"]["+col+"]:"+numbers[row][col]);
col++;
}
row++;
}
You can use something like this...
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
for (String element : numbers) {
sb.append(element);
sb.append(",");
}
br.write(sb.toString);
br.close();

Reading a space-delimited text file with blanks

I'm trying to read a text file which has tab space as delimiter but some values are left blank in it, how do i identify that value is left blank while reading the file. Please check my code below
FileReader file = new FileReader(new File("File.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
Please help me in pointing out the values that are left blank.
This looks like a CSV file, but instead of commas, are tabs. You can use opencsv for read the file.
CSVReader reader = new CSVReader(new FileReader("file.txt"), '\t');
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
The columns with blank value as empty strings in the array.
Or more simple:
CSVReader reader = new CSVReader(new FileReader("file.txt"), '\t');
List<String[]> all = reader.readAll();
Using #HunterMcMillen hint:
FileReader file = new FileReader(new File("File.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
String[] tabSeparatedArray = temp.split("\t")
foreach(String tabElement : tabSeparatedArray){
if (tabElement.trim().length <= 0){
//here the element is blank... do whatever you want!!!!
}
}
System.out.println(temp);
temp = br.readLine();
}

Optimized I/O operation in Java?

I have a file "a.txt" which contains the following lines:
14,15,16,17
13,16,15,14
15,17,12,13
...
...
I know that each line will always have 4 columns.
I have to read this file and split the lines based on delimiter (here it is ",") and write the value of each column in its corresponding file i.e. if value in a column is 14 then it has to be dumped/wriiten in 14.txt, if its 15 then it will be written in 15.txt and so on.
Here is what I have done till now:
Map <Integer, String> filesMap = new HashMap<Integer, String>();
for(int i=0; i < 4; i++)
{
filesMap.put(i, i+".txt");
}
File f = new File ("a.txt");
BufferedReader reader = new BufferedReader (new FileReader(f));
String line = null;
String [] cols = {};
while((line=reader.readLine()) != null)
{
cols = line.split(",");
for(int i=0;i<4;i++)
{
File f1 = new File (filesMap.get(cols[i]));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f1)));
pw.println(cols[i]);
pw.close();
}
}
So for line number 1 of file "a.txt", I will have to open, write and close files 14.txt,15.txt,16.txt and 17.txt
Again for line number 2, I have to again open,write and close files 14.txt,15.txt,16.txt and a new file 13.txt
So is there any better option in which I don't have to open and close the file which has already been opened earlier.
At the end of the complete operation I will close all the opened files.
Something like this should work:
Map <Integer, PrintWriter> filesMap = new HashMap<>();
...
if(!filesMap.containsKey(cols[i]))
{
//add a new PrintWriter
} else
{
//use the existing one
}
try
Set<String> s = new HashSet<>();
Scanner sc = new Scanner(new File ("a.txt")).useDelimiter("[\n\r,]+");
while(sc.hasNext()) {
String n = sc.next();
if (s.add(n)) {
FileWriter w = new FileWriter(n + ".txt");
w.write(n);
w.close();
}
}
sc.close();
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("a.txt");
BufferedReader reader = new BufferedReader(fr);
String line = "";
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
for (int i = 0; i < 4; i++) {
FileWriter fstream = new FileWriter(cols[i] + ".txt" , true);// true is for appending the data in the file.
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(cols[i] + "\n");
fbw.close();
}
}
}
Try this . I think you want to do like this way.

Categories

Resources