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;
}
}
Related
I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)
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;
}
}
How do I split a file input text into 2 different array? I want to make n array for the names, and an array for the phone numbers. I managed to do the file input, but ive tried everything and cant seem to split the names and the numbers, then put it into 2 different arrays. Im noob pls help
here is how the phonebook.txt file looks like
Bin Arry,1110001111
Alex Cadel,8943257000
Poh Caimon,3247129843
Diego Amezquita,1001010000
Tai Mai Shu,7776665555
Yo Madow,1110002233
Caup Sul,5252521551
This Guy,7776663333
Me And I,0009991221
Justin Thyme,1113332222
Hey Oh,3939399339
Free Man,4533819911
Peter Piper,6480013966
William Mulock,9059671045
below is my code
import java.io.*;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class demos {
public static void main(String[] args){
FileInputStream Phonebook;
DataInputStream In;
int i = 0;
String fileInput;
try
{
Phonebook = new FileInputStream("phonebook.txt");
FileReader fr = new FileReader("phonebook.txt");
BufferedReader br = new BufferedReader(fr);
String buffer;
String fulltext="";
while ((buffer = br.readLine()) != null) {
fulltext += buffer;
// System.out.println(buffer);
String names = buffer;
char [] Y ;
Y = names.toCharArray();
System.out.println(Y);
}}
catch (FileNotFoundException e)
{
System.out.println("Error - this file does not exist");
}
catch (IOException e)
{
System.out.println("error=" + e.toString() );
}
For a full functionnal (rather than imperative) solution I propose you this one :
public static void main(String[] args) throws IOException {
Object[] names = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[0]).toArray();
Object[] numbers = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[1]).toArray();
System.out.println("names in the file are : ");
Arrays.stream(names).forEach(System.out::println);
System.out.println("numbers in the file are : ");
Arrays.stream(numbers).forEach(System.out::println);
}
output
names in the file are :
Bin Arry
Alex Cadel
Poh Caimon
Diego Amezquita
Tai Mai Shu
Yo Madow
Caup Sul
This Guy
Me And I
Justin Thyme
Hey Oh
Free Man
Peter Piper
William Mulock
numbers in the file are :
1110001111
8943257000
3247129843
1001010000
7776665555
1110002233
5252521551
7776663333
0009991221
1113332222
3939399339
4533819911
6480013966
9059671045
As you can see functionnal programming is short and smart …. and easy when you're accustomed
You could simplify it if you are using Java 8:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
/**
* For each line, split it on the comma and send to splitNameAndNum()
*/
public static void main(String[] args) throws IOException {
Files.lines(new File("L:\\phonebook.txt").toPath())
.forEach(l -> splitNameAndNum(l.split(",")));
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}
And in Java 7:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("L:\\phonebook.txt")));
String line;
while ((line = br.readLine()) != null) {
splitNameAndNum(line.split(","));
}
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}
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();
}
}
How would I go about saving a String Vector to a file every time it is edited?
So let's say I have usernames in a vector, after I add or delete a username I'd like it to save that vector so if the program is closed, it will show the most recent elements.
This should help you get started.
As JB Nizet said, you should use an ArrayList.
I also went ahead and used Java 7 autocloseable functionality, which ensures you close file handles appropriately.
Of course, you will need to validate your input, and you will want to take care about what you persist. I suspect that you will soon want to consider a better storage strategy, however, this will get you started.
In addition, since this is acting like a collection, you should add hashcode and equals. For brevity sake, I did not add those.
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class PersistedCollection {
private static final String NEWLINE_SEPARATOR = System.getProperty("line.separator");
private final List<String> values;
private final File file;
public PersistedCollection(File file) {
this.values = new ArrayList<>();
this.file = file;
}
public void add(String value) {
// You should validate this value. Remove carriage returns, make sure it meets your value specifications.
values.add(value);
persist();
}
public void remove(String value) {
values.remove(value);
persist();
}
private void persist() {
// Using Java 7 autocloseable to ensure that the output stream is closed, even in exceptional circumstances.
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(this.file), 8192); Writer writer = new PrintWriter(outputStream)) {
for (String value : values) {
writer.append(value);
writer.append(NEWLINE_SEPARATOR);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PersistedCollection [values=");
builder.append(values);
builder.append(", file=");
builder.append(file);
builder.append("]");
return builder.toString();
}
public static void main(String[] arguments) {
PersistedCollection persistedCollection = new PersistedCollection(new File("/tmp/test.txt"));
persistedCollection.add("jazeee");
persistedCollection.add("temporary user");
persistedCollection.add("user402442");
persistedCollection.add("JB Nizet");
persistedCollection.remove("temporary user");
System.out.println(persistedCollection);
}
}
Another solution would be to create a class where you add all the methods required to read from a file of usernames (one username per line). Then you can refer to this class from anywhere (as the modifier is public) and call the methods such that you will add or remove usernames from that file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.io.File;
public class Test {
private static BufferedWriter bw;
private static ArrayList<String> vector=new ArrayList<String>();
private static String everything;
//add an username
public static void add(String x){
vector.add(x);
}
//remove an username
public static void remove(String x){
vector.remove(x);
}
//update the file with the new vector of usernames
public static void updateToFile() throws IOException{
File username = new File("/home/path/to/the/file");
FileWriter fw = new FileWriter(username.getAbsoluteFile());
bw= new BufferedWriter(fw);
for (String x:vector){
bw.write(x.toString());
bw.write("\n");
}
bw.close();
}
//you call this method to initialise your vector of usernames
//this implies that you already have a file of usernames
//one username per line
public static void setUsername() throws IOException{
vector=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("/home/path/to/the/file"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
} finally {
br.close();
}
String lines[] = everything.split("\\r?\\n");
for (String x:lines){
vector.add(x);
}
}
//print your usernames in the console
public static void printUsers(){
for (String User:vector){
System.out.println(User);
}
}
}
Then it gets as easy as this:
import java.io.IOException;
public class MainTest {
public static void main(String[] args) throws IOException{
Test.setUsername();
Test.printUsers();
Test.add("username5");
Test.remove("username2");
System.out.println("// add username5; remove username2");
Test.printUsers();
System.out.println("// file has been updated with the new state");
Test.updateToFile();
System.out.println("// veryfing update");
Test.setUsername();
Test.printUsers();
}
}
The output:
(this first 4 users is what I have in the file)
username1
username2
username3
username4
// add username5; remove username2
username1
username3
username4
username5
// file has been updated with the new state
// verifying update
username1
username3
username4
username5