It seems my IntelliJ cannot find my csv file? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So ive made a class to keep track of the data i've imported:
package com.company;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException{
String file = "Users/mathiaspoulsen/Desktop/SP3MarioPizza/pizzas.csv";
ArrayList <Pizza> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while ((line = br.readLine()) != null) {
line = br.readLine();
String [] lineArr = line.split(",");
Pizza pizza = new Pizza (Integer.parseInt(lineArr[0]),lineArr[1],Double.parseDouble(lineArr[2]));
content.add(pizza);
}
} catch (FileNotFoundException e) {
//Some error logging
}
return content;
}
I have then tried to run it in the main method to see if it loads the csv-file corectly. Like this:
package com.company;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
/* int i = 0;
String fileName = "pizzas.csv";
Path pathToFile = Paths.get(fileName);
System.out.println(pathToFile.toAbsolutePath());
*/
// ArrayList<Pizza> pizzas = ImportData.readData();
System.out.println(ImportData.readData());
}
}
The output of this program is: []
Why dont it display the pizzas? The pizzas in the csv-file a structured like this:
PizzaNumber(int),PizzaName(String), price(double)
1,MARGHERITA,69.00

You read the line multiple times which most likely was causing your issue just read the line once and check to make sure it is not null in the while statement before parsing it. Also, it would be better to check to make sure the parse is successful.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException {
String file = "/Users/your/path/pizza.csv";
ArrayList<Pizza> content = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] lineArr = line.split(",");
content.add(new Pizza(Integer.parseInt(lineArr[0]), lineArr[1], Double.parseDouble(lineArr[2])));
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
return content;
}
}

Related

java update txt file content line by line

I am trying to update a txt file in place, namely without creating a temp file or writing a file in a new file destination but I've tried all the solutions on stack overflow and none of these have worked so far.
It always give me an empty file as result. it simply delete all the content of the source file.
So I am trying to modify the following code, which takes two files as input, in order to take only one input (the file source) but without success.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class CopyFiles {
private static void copyFile(String sourceFileName, String destinationFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(sourceFileName));
PrintWriter pw = new PrintWriter(new FileWriter(destinationFileName))) {
String line;
while ((line = br.readLine()) != null) {
line += " ENDING ";
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String destinationFileName = "destination.csv";
String sourceFileName = "source.csv";
copyFile(sourceFileName, destinationFileName);
}
}

My HTML fetcher program in java returns incomplete results

My java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class celebGrepper {
static class CelebData {
URL link;
String name;
CelebData(URL link, String name) {
this.link=link;
this.name=name;
}
}
public static String grepper(String url) {
URL source;
String data = null;
try {
source = new URL(url);
HttpURLConnection connection = (HttpURLConnection) source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
/**
* Attempting to fetch an entire line at a time instead of just a character each time!
*/
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while((data = br.readLine()) != null)
str.append(data);
data=str.toString();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static ArrayList<CelebData> parser(String html) throws MalformedURLException {
ArrayList<CelebData> list = new ArrayList<CelebData>();
Pattern p = Pattern.compile("<td class=\"image\".*<img src=\"(.*?)\"[\\s\\S]*<td class=\"name\"><a.*?>([\\w\\s]+)<\\/a>");
Matcher m = p.matcher(html);
while(m.find()) {
CelebData current = new CelebData(new URL(m.group(1)),m.group(2));
list.add(current);
}
return list;
}
public static void main(String... args) throws MalformedURLException {
String html = grepper("https://www.forbes.com/celebrities/list/");
System.out.println("RAW Input: "+html);
System.out.println("Start Grepping...");
ArrayList<CelebData> celebList = parser(html);
for(CelebData item: celebList) {
System.out.println("Name:\t\t "+item.name);
System.out.println("Image URL:\t "+item.link+"\n");
}
System.out.println("Grepping Done!");
}
}
It's supposed to fetch the entire HTML content of https://www.forbes.com/celebrities/list/. However, when I compare the actual result below to the original page, I find the entire table that I need is missing! Is it because the page isn't completely loaded when I start getting the bytes from the page via the input stream? Please help me understand.
The Output of the page:
https://jsfiddle.net/e0771aLz/
What can I do to just extract the Image link and the names of the celebs?
I know it's an extremely bad practice to try to parse HTML using regex and is the stuff of nightmares, but on a certain video training course for android, that's exactly what the guy did, and I just wanna follow along since it's just in this one lesson.

Calling method from different class (different than other questions)

So I'm relatively new to java and I'm trying to use a method from a different class inside my main.
The method I'm using to pull doesn't contain any data initially but pulls the data from a text doc.
I've included the code that calls the other class method that loads the data from the file. It sill doesn`t work, so where is my mistake?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
//output of animalList class here
}
Here is the class I'm trying to pull from:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public void animalDetails () {
int i = 0;
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "‪C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
StringBuilder animalDetailList = new StringBuilder();
String line;
while ((line = animalList.readLine()) != null) {
for (i = 0; i <4 ; i++) {
System.out.println(line);
animalList.readLine();
}
}
animalReader.close();
System.out.println(animalDetailList.toString());
}
catch (IOException e) {
}
}
}
So I want to have the output of the animalList class in my main, but I don't know how to bring it over because I'm not necessarily bring over variable, but a process. The full thing should bring the first line and four past it (so a total of the first five lines in the doc). Hopefully that makes things easier to see my problem.
This is a mcve of AnimalList :
public class AnimalList {//use java naming convention
public void animalDetails () {
//mcve should be runnable. The problem you ask help with is not
//reading from file, so remove file reading functionality to make it mcve
StringBuilder animalDetailList = new StringBuilder();
animalDetailList.append("Family: Cats").append("\n")
.append("Type : Panther").append("\n")
.append("Weight: 250kg").append("\n")
.append("Color : Pink");
System.out.println(animalDetailList.toString());
}
}
Invoke its method from another class:
public class FinalRobert {
public static void main(String[] args) {
//to invoke animalDetails() method use
AnimalList aList = new AnimalList();
aList.animalDetails();
//if you do not need the aList refrence you could use
//new AnimalList().animalDetails();
}
}
Output
Family: Cats Type : Panther Weight: 250kg Color :
Pink
I hope this might help you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
animalList list = new animalList();
list.animalDetails();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public String animalDetails () {
int i = 0;
String output="";
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "‪C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
String line;
while ((line = animalList.readLine()) != null & i<4) {
System.out.println(line);
output = output + "\n"+ line;
i++;
}
animalReader.close();
System.out.println(output);
}
catch (IOException e) {
}
return output;
}
}

Java - Merging two sets of code

I've written two separate pieces of code. Now I want to merge both pieces of code. Now one part opens a text file and displays the contents of the text file and the second piece of code validates manually entered postcodes. Now I want to read a text file and then automatically validate postcodes within the text file. Not sure how I can merge them. Any questions please ask as I'm stuck.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
System.out.println(str + "");
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
// Close the input
}
}
Second part that manually validates postcodes:
List<String> zips = new ArrayList<String>();
//Valid ZIP codes
zips.add("SW1W 0NY");
zips.add("PO16 7GZ");
zips.add("GU16 7HF");
zips.add("L1 8JQ");
//Invalid ZIP codes
zips.add("Z1A 0B1");
zips.add("A1A 0B11");
String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
Pattern pattern = Pattern.compile(regex);
for (String zip : zips)
{
Matcher matcher = pattern.matcher(zip);
System.out.println(matcher.matches());
}
You should create a class called something like ZipCodeValidator that contains the functionality of your second snippet. It will look something like this
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
Then you can create an instance of this class
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
and then use it in your main method
boolean valid = zipCodeValidator.isValid(zipCode);
Merging your question and the answer by #hiflyer I posted this answer, this makes an assumption that the file postcodes1.txt has all the zip codes in separate lines.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
if(zipCodeValidator.isValid(str)){
System.out.println(str + " is valid");
}
else{
System.out.println(str + " is not valid");
}
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
}
}
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}

Reading numbers from a file and creating an array (java)

I cannot figure out how to make this txt file with numbers into an array, I am able to get it to read and print the screen but I need to be able to organize the numbers and delete the duplicates. This is what my code looks like so far
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
System.out.format(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
}
}
}
I would recommend using an ArrayList rather than an Array.
With an array you would have to parse through the list and calculate the line count before you could even initialize it. An ArrayList is much more flexible as you don't have to declare how many values will be added to it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File {
private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input));//Add each parsed number to the arraylist
System.out.println(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
ex.printstacktrace(); //Usually good for general handling
}
}
}

Categories