Im working on a task that requires me to read from a .csv file using stream API, go over each line and construct an object with the lines. The object class is called Planet and is:
public Planet(String name, long inhabitants, boolean stargateAvailable, boolean dhdAvailable, List<String> teamsVisited) {
}
public String getName() {
return name;
}
public long getInhabitants() {
return inhabitants;
}
public boolean isStargateAvailable() {
return stargateAvailable;
}
public boolean isDhdAvailable() {
return dhdAvailable;
}
public List<String> getTeamsVisited() {
return teamsVisited;
}
#Override
public String toString() {
return name;
}
}
So using stream API to go over each of the lines of the .cvs file i need to create objects of class Planet.
I havent made any progress at all because I really am not sure how to use stream API
public class Space {
public List<Planet> csvDataToPlanets(String filePath) {
return null;
}
try the below snippet.
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());
br.close();
For more information check this link
public static void main(String args[]) {
String fileName = "<Your File Path"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(<Method to split the string based with ',' as delimiter and call Constructor using Reflection API>);
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I am attempting to use the method "public boolean readArtists" with a scanner to read strings from a file and return true if opened successfully. This method is also supposed to "Adds to the list all of the artists stored in the file passed parameter."
I've seen how to write the code in a public static void method that will read the text file and return it:
public static void main(String[] args) {
File file = new File("artists30.txt");
String content = null;
try {
try (Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name())) {
content = scanner.useDelimiter("\\A").next();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
}
Here is the test:
I have to keep the method "public boolean readArtists(String filename), so my question is, within this method, how do I read the contents of the text file into an ArrayList using a scanner, while also returning true if the file is opened successfully, Otherwise, handling the exception, displaying an appropriate error message containing the name of the missing file and return false.
public class Artists{
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("filename goes here"));
System.out.println(artists);
}
public Artists(String artist, String genre)
{
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if(file.createNewFile()) {
System.out.println("err "+fileName);
return false;
}
sc = new Scanner(file);
while(sc.hasNextLine()) {
artists.add(sc.nextLine());
}
}catch(Exception e) {
e.printStackTrace();
}
if(sc!=null) {sc.close();}
return true;
}
}
This answer reads data from a .txt document into an ArrayList, as long as the .txt document names are on seperate lines in the document. It also outputs err \FILE\NAME and returns false if the document does not exist and true if it does. https://www.w3schools.com/java/java_files.asp is a great website to learn java by the way and this link brings you to the file handling page.
You can achieve that using,
public static void main(String[] args) throws FileNotFoundException {
String filepath = "C:\\Users\\Admin\\Downloads\\testFile.txt";
List<String> arrayList = new ArrayList<>();
if(readArtists(filepath)) {
Scanner sc = new Scanner(new File(filepath));
sc.useDelimiter("\\A");
while(sc.hasNext()) {
arrayList.add(sc.next());
}
}
System.out.println(arrayList);
}
public static boolean readArtists(String filename)
{
File file = new File(filename); //full path of the file with name
return file.canRead();
}
I´m writing my own library in java, where you can save variables very simple. But I have a problem in changing the values of the variables. The ArrayList empties itself as soon as the txt file is empty.
My Code:
public class SaveGameWriter {
private File file;
private boolean closed = false;
public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
{
if(!reader.read(savegamefile).contains(variableName))
{
file = savegamefile.getFile();
OutputStream stream = new FileOutputStream(file, true);
try {
String text = variableName+"="+variableValue;
stream.write(text.getBytes());
String lineSeparator = System.getProperty("line.separator");
stream.write(lineSeparator.getBytes());
}catch(IOException e)
{}
do {
try {
stream.close();
closed = true;
} catch (Exception e) {
closed = false;
}
} while (!closed);
}
}
public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
{
ArrayList<String> list = reader.read(savegamefile);
if(list.contains(variableName))
{
list.set(list.indexOf(variableName), Value);
savegamefile.clear();
for(int i = 0; i<list.size()-1;i+=2)
{
write(savegamefile,list.get(i),list.get(i+1),reader);
}
}
}
}
Here my SaveGameReader class:
public class SaveGameReader {
private File file;
private ArrayList<String> result = new ArrayList<>();
public String getValueOf(SaveGameFile savegamefile, String variableName)
{
ArrayList<String> list = read(savegamefile);
if(list.contains(variableName))
{
return list.get(list.indexOf(variableName)+1);
}else
return null;
}
public ArrayList<String> read(SaveGameFile savegamefile) {
result.clear();
file = savegamefile.getFile();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("=");
for (String part : splited) {
result.add(part);
}
}
} catch (IOException e) {
} finally {
boolean closed = false;
while(!closed)
{
try {
in.close();
closed=true;
} catch (Exception e) {
closed=false;
}
}
}
result.remove("");
return result;
}
}
And my SaveGameFile class:
public class SaveGameFile {
private File file;
public void create(String destination, String filename) throws IOException {
file = new File(destination+"/"+filename+".savegame");
if(!file.exists())
{
file.createNewFile();
}
}
public File getFile() {
return file;
}
public void clear() throws IOException
{
PrintWriter pw = new PrintWriter(file.getPath());
pw.close();
}
}
So, when I call the setValueOf() methode the ArrayList is empty and in the txt file there´s just the first variable + value. Hier´s my data structure:
Name=Testperson
Age=40
Phone=1234
Money=1000
What´s the problem with my code?
In your SaveGameReader.read() method you have result.clear(); which clears ArrayList. And you do it even before opening the file. So basically before every read from file operation you are cleaning up existing state and reread from file. If file is empty then you finish with empty list
I am working on a project to get into android development, having some knowledge of java before I am thinking of reading data from a text file, which will be formatted like this;
Type: House
Image link: www.bit.ly/image1
Name: Black
Download Link: www.bit.ly/image1download
----------
Type: Car
Image link: www.bit.ly/image2
Name: yellow
Download Link: www.bit.ly/image2download
----------
Type: Backyard
Image link: www.bit.ly/image3
Name: Green
Download Link: www.bit.ly/image3download
----------
Type: Window
Image link: www.bit.ly/image4
Name: Solid
Download Link: www.bit.ly/image4download
----------
Type: Table
Image link: www.bit.ly/image5
Name: Brown
Download Link: www.bit.ly/image5download
----------
The data contains 4 pieces of information per set, Type, Image, Name and Download. I need a way of reading this and saving/writing it to a arraylist which I then can display in a listview that I will have on my app. (I am currently looking at tutorials on creating listview, if you know any useful tutorials please let me know)
Arraylist <String> data = new ArrayList<String>();
Data.add(“House”,” www.bit.ly/image1”,”black”,”www.bit.ly/image1download”);
Data.add(“Car”,” www.bit.ly/image2”,”yellow”,” www.bit.ly/image2download”);
……..
……..
In reality there will be a lot more data then just 5 sets , so I want to use for loop to loop through each data data and add it to the data arraylist.
I am not sure how I can approach this, any help is welcomed, I am really stuck. Please let me know if I have not explained my question properly.
EDITED:
Would this be the correct way of reading data from a textfile?
Scanner content = new Scanner(new File("Data.txt"));
ArrayList<String> data = new ArrayList<String>();
while (content.hasNext()){
data.add(content.next());
}
content.close();
Or is this another way in android
Before start go through this link for reading
How can I read a text file in Android?
Use PoJo Models for your needs,
Create a PoJo class like this
public class Film {
private String filmName;
private String mainStar;
public String getFilmName() {
return filmName;
}
public void setFilmName(String filmName) {
this.filmName = filmName;
}
public String getMainStar() {
return mainStar;
}
public void setMainStar(String mainStar) {
this.mainStar = mainStar;
}
}
Create ArrayList
private ArrayList<Film > filmArray=new ArrayList<Film>();
Store Each arraylist with instance of your PoJo class like this
for(int i=0;i<sizei++)
{
Film film=new Film();
film.setFilmName("your value");
film.setMainStar("your value");
filmArray.add(film);
}
and then access list of values in arraylist of PoJo class in filmArray list.
Simple and elegant solution.
Here is the parser
public class FileParser {
private static final String DATA_TERMINATION = "----------";
private static final String TYPE="Type";
private static final String IMAGE="Image link";
private static final String NAME= "Name";
private static final String DWNLD_LNK= "Download Link";
public static void main(String[] args) {
FileParser parser = new FileParser();
try {
for(Data d:parser.parseDataFile(new File("F:\\data.txt"))){
System.out.println(TYPE+":"+d.getType());
System.out.println(IMAGE+":"+d.getImage());
System.out.println(NAME+":"+d.getName());
System.out.println(DWNLD_LNK+":"+d.getLink());
System.out.println(DATA_TERMINATION);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<Data> parseDataFile(File input) throws Exception{
List<Data> output =null;
List<String> fileOp= null;
try {
validateInput(input);
fileOp = readFile(input);
output = parseData(fileOp);
} catch (Exception e) {
throw e;
}
return output;
}
private List<Data> parseData(List<String> fileOp) {
List<Data> output =null;
output = new ArrayList<Data>();
Data data;
data = new Data();
for(String line:fileOp){
if(DATA_TERMINATION.equalsIgnoreCase(line)){
output.add(data);
data = new Data();
}else{
parseField(data,line);
}
}
return output;
}
private void parseField(Data data, String line) {
StringTokenizer tokenzr = new StringTokenizer(line,":");
if(tokenzr.countTokens() !=2){
System.out.println("Cant parse line"+line);
}else{
switch (tokenzr.nextToken()) {
case TYPE:
data.setType(tokenzr.nextToken());
break;
case IMAGE:
data.setImage(tokenzr.nextToken());
break;
case NAME:
data.setName(tokenzr.nextToken());
break;
case DWNLD_LNK:
data.setLink(tokenzr.nextToken());
break;
default:
break;
}
}
}
private List<String> readFile(File input) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
String line = null;
List<String> op = new ArrayList<String>();
try {
while((line = reader.readLine()) != null){
op.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
return op;
}
private void validateInput(File input) throws Exception {
if(input == null){
throw new Exception("Null input");
}else if(!input.exists() || !input.isFile() || !input.canRead() ) {
throw new Exception("File not readable");
}
}
}
Do this way define a setter getter class to hold and return values like this :
Data.class
public class Data {
String type,Image,Name,Link ;
public Data() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
}
using for loop set data in a arraylist
Arraylist <Data> arrayListData = new ArrayList<Data>();
for(int i=0;i<arrayListData .size();i++){
Data data=new Data();
data.setType("");
...
...
...
arrayListData.add(data);
}
and to fetch data from arraylist
String type= arrayListData.get(position).getType();
Updated :
read .txt file like this , I am assuming your text file is saved in sdcard of device :
public void readfile() {
StringBuilder text = new StringBuilder();
File sdcard = Environment.getExternalStorageDirectory();
ArrayList<Data> arrayList=new ArrayList<Data>();
//Get the text file
File file = new File(sdcard,"textfile.txt");
//Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
Data data=new Data();
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
if(line.contains(":")){
int index=line.indexOf(":");
String s=line.substring(index+1).trim();
if(line.contains("Type")){
data.setType(s);
}
if(line.contains("Image")){
data.setImage(s);
}
if(line.contains("Name")){
data.setName(s);
}
if(line.contains("Download")){
data.setLink(s);
}
}
if(line.contains("-")){
arrayList.add(data);
data=new Data();
}
}
System.out.println(text);
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
I'm doing a project for a class, but for the life of me I'm having the hardest time figuring out how to read text from a file. We have to create a traffic light that queues trucks and cars coming from North, South, East, and West. It's been a long time since I've done any coding, so I'm struggling immensely. I think it just reads the memory location. Here's my code for reading in a file.
package Project1;
import java.io.*;
import java.util.*;
public class TrafficSim {
public String input;
public TrafficSim(String input)
{
this.input = input;
readFromFile();
}
private boolean readFromFile()
{
File inputText = new File("input1.txt");
try
{
Scanner scan = new Scanner(inputText);
while(scan.hasNextLine())
{
String direction = scan.nextLine();
int num = scan.nextInt();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim);
}
}
Your method readFromFile sure enough reads from a file, but then it doesn't do anything. All you do is read line by line, storing a line of text and an int in variables which are forgotten after each iteration of your while loop.
Your code System.out.println(sim) prints out whatever the toString method of your class returns, and since you didn't override that method it will print out the result of Object.toString, which is not what you want.
To put it simply, you're reading from a file but you're not doing anything with the contents that you read.
Here is what I would do....
public class TrafficSim {
private String input;
private String content;
public TrafficSim(String input) {
this.setInput(input);
this.setContent(readFromFile());
}
private String readFromFile() {
File inputText = new File(input);
StringBuilder sb = new StringBuilder();
try {
Scanner scan = new Scanner(inputText);
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public static void main(String[] args) {
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim.getContent());
}
}
The issue I see though is that you're not following the comments and suggestions already made. ktm5124 was pretty clear on what the problem is. At some point you're going to have to understand what is going on here and how to fix it.