Fill Array From Text File Depending On Character's Gender - java

I want to fill an array with names. The array should be filled depending on what gender the character is.
public void fillNameArray() throws IOException {
Character character = new Character(); //Declare and initialise character object
if(character.getGender() == "F"){
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("femaleNames.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = (String[]) lines.toArray();
}
else{
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("maleNames.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = (String[]) lines.toArray();
}
}

The problem is in the following line:
String[] array = (String[]) lines.toArray();
Write instead:
String[] array = lines.toArray(new String[lines.size()]);
See post as example.
Please can you also move the read code on a own method? So less code duplication.
public List<String> readNames(String file) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
return lines;
}

Related

String from CSV into array (Java)

I am trying to put column values (CSV file) into an array.
The CSV file:
My code:
public void readFile1()
{
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] passengerDetails = line.split(cvsSplitBy);
bookingDetails pd = new bookingDetails(passengerDetails[0], passengerDetails[1], passengerDetails[2], passengerDetails[3]);
String x = passengerDetails[2];
System.out.println(passengerDetails[2]); // how to put these values inside an array
}
} catch (IOException e) {
e.printStackTrace();
}}
The output of my code:

How do I get the single element from the text file by using ArrayList?

My text file includes:
Mary,123,s100,59.2
Melinda,345,A100,10.1
Hong,234,S200,118.2
Ahmed,678,S100,58.5
Rohan,432,S200,115.5
Peter,654,S100,59.5
My code:
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("competitors.txt")) ;
String line;
ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
lines.add(line);
}
String[] lineobject= {lines.get(0)};
System.out.println(lineobject[0]);
}
}
I don't know why it can not get the single value of first row, can anyone help?Thanks.
lines.get(0) is "Mary,123,s100,59.2", not {"Mary","123","s100","59.2"}
So you should do;
String[] lineobjects = lines.get(0).split(",");
System.out.println(lineobjects);
System.out.println(lineobjects[0]); // prints "Mary"
Your code works fine for me. However, you should make sure to place the file competitors.txt in the right directory.
This is simpler and should also do the job:
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("competitors.txt"));
System.out.println(lines.get(0));
}
You may replace the line with some another signs instead of using, (I use %in my case),and split using.split("%"),Then store in a vector file..
Vector data;
Vector columns;
String line;
data = new Vector();
columns = new Vector();
try {
FileInputStream fis = new FileInputStream(PRJT_PATH+"\\YOUR\\PROJECT\\"+PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
int i=0;
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens()){
data.addElement(st2.nextToken());}
String clr[]=line.split("%");
Vector v=new Vector();
v.add(clr[0]);
v.add(clr[1]);
i++;
}
br.close();
fis.close();
} catch (Exception e) {
e.getMessage();
}

How to append multiple text in text file

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".

Read text file line by line and store in a class?

I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.

UTF-8 : characters not recognized

I am trying to parse a text file using HashMap. The problem is that I have special characters like Ș and Ț and my application didn't recognize them.
This is my code:
Map<String, String> m = new LinkedHashMap<String, String>();
FileInputStream fin = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fin = new FileInputStream("inferredflexforms.txt");
isr = new InputStreamReader(fin, "UTF-8");
br = new BufferedReader(isr);
String line = br.readLine();
while (line != null) {
String[] toks = line.split("\\s+");
m.put(toks[0], toks[1]);
line = br.readLine();
}
} finally {
if (br != null) { br.close(); }
if (isr != null) { isr.close(); }
if (fin != null) { fin.close(); }
}
System.out.println(m);
My text file contains: dănțaseși dansa
And my output is: dăn?ase?i=dansa
The "ș" and "ț" was replaced by "?".
What should I do?
Thank you.

Categories

Resources