I wanted to ask how I can load information of a csv-file in a list. I don't have much until now so a little help would be nice if possible. What I tried until now is to get the file but I'm not sure if it's right because I'm not that good at File I/O. After that I stuck at how to save it in a list.
List<GameCharacter> characters;
static void loadTextFile(String textFile) throws FileNotFoundException {
//textFile = String.valueOf(new File("C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv"));
textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
FileInputStream d = new FileInputStream(textFile);
}
Not sure if you have any limitations on what you can use and what can't but did you try using OpenCSV library?
You can then read it like this
try (CSVReader reader = new CSVReader(new FileReader("file.csv"))) {
List<String[]> r = reader.readAll();
r.forEach(x -> System.out.println(Arrays.toString(x)));
}
This will give you a list of array of strings which will contain all the values for each line.
You can use Scanner like this
textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
List<List<String>> mylist = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("textFile"));) {
while (scanner.hasNextLine()) {
mylist.add(getRecordFromLine(scanner.nextLine()));
}
}
You can also use BufferedReader in java.io like the following
textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
List<List<String>> myList = new ArrayList<>();
try (BufferedReader bffuerReader = new BufferedReader(new FileReader("textFile"))) {
String line;
while ((line = bffuerReader.readLine()) != null) {
String[] values = line.split(COMMA_DELIMITER);
myList.add(Arrays.asList(values));
}
}
I'm currently working on a program that reads in a preset text file and then manipulates the data in various ways. I've got the data manipulation to work with some dummy data but I still need to get the text file read in correctly.
The test file looks like this for 120 lines:
Aberdeen,Scotland,57,9,N,2,9,W,5:00,p.m. Adelaide,Australia,34,55,S,138,36,E,2:30,a.m. Algiers,Algeria,36,50,N,3,0,E,6:00,p.m.(etc etc)
So each of these needs to be read into its own array, in order String[] CityName,String[] Country,int[] LatDeg,int[] LatMin,String[] NorthSouth,int[] LongDeg,int LongMin,String[] EastWest,int[] Time.String[] AMPM
So the problem is that while I'm reasonably comfortable with buffered readers, designing this particular function has proven difficult. In fact, I've been drawing a blank for the past few hours. It seems like it would need multiple loops and counters but I can't figure out the precisely how.
I am assuming that you have one city per line type of file structure. If it is not, it will require a bit of tweaking in the following solution:
I will do the following way if I am more comfortable with BufferReader as you say:
List<List<String>> addresses = new ArrayList<List<String>>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
addresses.add(line.split(","));
}
}
Later, let's say you want to retrieve the country information of say 'Adelaid', you can try the following:
for (List<String> cityInfo : addresses) {
if("Adelaid".equals(cityInfo.get(0)) {
country = cityInfo.get(1);
}
}
Instead of creating different arrays (like String[] CityName,String[] Country, etc.,), try using a Domain Object.
Here, you can have a Domain object or Custom class Location with attributes
public class Location
{
private String cityName;
private String country;
private String latDeg;
etc
getters();
setters();
}`
Then you can write a file reader, each line item in the file will be a Location. So result will have
Location[] locations;
or
List locations;`
To carry out this task I should think the first thing you want to do is establish how many lines of data actually exist within the data file. You say it is 120 lines but what if it happens that it will be more or less? We would want to know exactly what it is so as to properly initialize all our different Arrays. We can use a simple method to accomplish this, let's call it the getFileLinesCount() method which will ulitmately return a Integer value that would be the number of text lines the data file holds:
private int getFileLinesCount(final String filePath) {
int lines = 0;
try{
File file =new File(filePath);
if(file.exists()){
FileReader fr = new FileReader(file);
try (LineNumberReader lnr = new LineNumberReader(fr)) {
while (lnr.readLine() != null){ lines++; }
}
}
else {
throw new IllegalArgumentException("GetFileLinesCount() Method Error!\n"
+ "The supplied file path does not exist!\n(" + filePath + ")");
}
}
catch(IOException e){ e.printStackTrace(); }
return lines;
}
Place this method somewhere within your main class. Now you need to Declare and initialize all your Arrays:
String filePath = "C:\\My Files\\MyDataFile.txt";
int lines = getFileLinesCount(filePath);
String[] CityName = new String[lines];
String[] Country = new String[lines];
int[] LatDeg = new int[lines];
int[] LatMin = new int[lines];
String[] NorthSouth = new String[lines];
int[] LongDeg = new int[lines];
int[] LongMin = new int[lines];
String[] EastWest = new String[lines];
int[] Time = new int[lines];
String[] AMPM = new String[lines];
Now to fill up all those Arrays:
public static void main(String args[]) {
loadUpArrays();
// Do whatever you want to do
// with all those Arrays.....
}
private void loadUpArrays() {
// Read in the data file.
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String sCurrentLine;
int x = 0;
// Read in one line at a time and Fill the Arrays...
while ((sCurrentLine = br.readLine()) != null) {
// Split each line read into an array upon itself.
String[] fileLine = sCurrentLine.split(",");
// Fill our required Arrays...
CityName[x] = fileLine[0];
Country[x] = fileLine[1];
LatDeg[x] = Integer.parseInt(fileLine[2]);
LatMin[x] = Integer.parseInt(fileLine[3]);
NorthSouth[x] = fileLine[4];
LongDeg[x] = Integer.parseInt(fileLine[5]);
LongMin[x] = Integer.parseInt(fileLine[6]);
EastWest[x] = fileLine[7];
Time[x] = Integer.parseInt(fileLine[8]);
AMPM[x] = fileLine[9];
x++;
}
br.close();
}
catch (IOException ex) { ex.printStackTrace(); }
}
Now, I haven't tested this, I just quickly punched it out but I think you can get the jest of it.
EDIT:
As #Mad Physicist has so graciously pointed out within his comment below, a List can be used to eliminate the need to count file lines therefore eliminating the need to read the data file twice. All the file lines can be placed into the List and the number of valid file lines can be determined by the size of the List. Filling of your desired arrays can now also be achieved by iterating through the List elements and processing the data accordingly. Everything can be achieved with a single method we'll call fillArrays(). Your Arrays declaration will be a little different however:
String[] CityName;
String[] Country;
int[] LatDeg;
int[] LatMin;
String[] NorthSouth;
int[] LongDeg;
int[] LongMin;
String[] EastWest;
String[] Time;
String[] AMPM;
public static void main(String args[]) {
fillArrays("C:\\My Files\\MyDataFile.txt");
// Whatever you want to do with all
// those Arrays...
}
private void fillArrays(final String filePath) {
List<String> fileLinesList = new ArrayList<>();
try{
File file = new File(filePath);
if(file.exists()){
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String strg;
while((strg = br.readLine()) != null){
// Make sure there is no blank line. If not
// then add line to List.
if (!strg.equals("")) { fileLinesList.add(strg); }
}
br.close();
}
}
else {
throw new IllegalArgumentException("GetFileLinesCount() Method Error!\n"
+ "The supplied file path does not exist!\n(" + filePath + ")");
}
// Initialize all the Arrays...
int lines = fileLinesList.size();
CityName = new String[lines];
Country = new String[lines];
LatDeg = new int[lines];
LatMin = new int[lines];
NorthSouth = new String[lines];
LongDeg = new int[lines];
LongMin = new int[lines];
EastWest = new String[lines];
Time = new String[lines];
AMPM = new String[lines];
// Fill all the Arrays...
for (int i = 0; i < fileLinesList.size(); i++) {
String[] lineArray = fileLinesList.get(i).split(",");
CityName[i] = lineArray[0];
Country[i] = lineArray[1];
LatDeg[i] = Integer.parseInt(lineArray[2]);
LatMin[i] = Integer.parseInt(lineArray[3]);
NorthSouth[i] = lineArray[4];
LongDeg[i] = Integer.parseInt(lineArray[5]);
LongMin[i] = Integer.parseInt(lineArray[6]);
EastWest[i] = lineArray[7];
Time[i] = lineArray[8];
AMPM[i] = lineArray[9];
}
}
catch(IOException e){ e.printStackTrace(); }
}
On another note...your Time Array can not be Integer since in data, what is considered the time contains a colon (:) which is a alpha character therefore (in case you haven't noticed) I have changed its declaration to String[]
In my code I have two files in my drive those two files have some text and I want to display those string in the console and also remove the repeated string and display the repeated string once rather than displaying it twice.
Code:
public class read {
public static void main(String[] args) {
try{
File file = new File("D:\\file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = br.readLine()) != null){
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file1:");
String first = stringBuffer.toString();
System.out.println(first);
File file1 = new File("D:\\file2.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader br1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer1 = new StringBuffer();
String line1;
while((line1 = br1.readLine()) != null){
stringBuffer1.append(line1);
stringBuffer1.append("\n");
}
fileReader1.close();
System.out.println("Contents of file2:");
String second = stringBuffer1.toString();
System.out.println(second);
System.out.println("answer:");
System.out.println(first+second);
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Output is:
answer:
hi hello
how are you
hi ya
i am fine
But I want to compare both the strings and if the same string repeated then that string should be displayed once.
Output I expect is like this:
answer:
hi hello
how are you
ya
i am fine
Where the "hi" is found in both the strings so that I need to delete the one duplicate string.
How can I do that please help.
Thanks in advance.
You can pass your lines through this method to parse out duplicate words:
// store unique previous words
static Set<String> words = new HashSet<>();
static String removeDuplicateWords(String line) {
StringJoiner sj = new StringJoiner(" ");
// split on whitespace to get distinct words
for (String word : line.split("\\s+")) {
// try to add word to the set
if (words.add(word)) {
// if the word was added (=not seen before), append to the result
sj.add(word);
}
}
return sj.toString();
}
I have this simple bit of code causing me a headache
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("Quiz.csv")));
List<String> lines = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
catch (Exception e)
{
Log.e(getLocalClassName(), e.toString());
}
I get a nullPointerException from logcat when I hit the while loop
Your lines is null. Initialise it:
List<String> lines = new ArrayList<String>();
You have to initialize lines like so:
List<String> lines = new ArrayList<String>();
I have a text file which is read in. It has delimeters which are <.> . There is a main subject then there are three paragraphs. Lets say title, section1, section2, section3, and then the next article.
How can I store the data so that ArrayList one will have all the titles, ArrayList 2 will have all the section1 information, etc.? I want be able to output these arrays.
E.g.:
Large storm on its way.
about the large storm
statics on storms
conclusions about storms
The example above shows what one record would look like.
public void read()
{
try
{
FileReader fr = new FileReader(file_path);
BufferedReader br = new BufferedReader(fr);
String s = "";
// keep going untill there is no input left and then exit
while((s = br.readLine()) != null)
{ }
fr.close();
}
catch (Exception e)
{
System.err.println("Error: read() " + e.getMessage());
}
}
public static void main(String [] args)
{
Reader reader = new ResultsReader("C:/data.txt");
reader.read();
String output = ((ResultsReader)reader).getInput();
String str = "title<.>section1<.>section2<.>";
String data[] = str.split("<.>");
}
I am not sure how to store the data in separate ArrayLists so that they can be traversed.
You cannot create arrays and put the data into them, because you don't know how large to create the arrays. So, use a list instead and then turn them into arrays after you have finished reading the file:
List tilesList = new ArrayList<String>();
// etc.
FileReader fr = new FileReader(file_path);
BufferedReader br = new BufferedReader(fr);
String s = null // I think this should be null, so that if there are no lines,
// you don't have problems with str.split();
while((s = br.readLine()) != null) {
String[] line = str.split("<.>");
tilesList.add(line[1]);
// etc.
}
fr.close();
String[] tiles = tilesList.toArray(new String[tilesList.size()]);
// etc.