I currently need to import data from a CSV file into an array as an object. The data is not all of the same type however and one line of the data is formatted like this "Tom, Jones, 95846, 657.45". I am able to parse the file but cannot seem to figure out how to store this data into an array. I will need to sort this data later on based on different requirements like Name and Number.
import java.io.*;
import java.util.*;
public class People {
public static void main(String[] args) {
File file = new File("People.csv");
People peopleArr[] = new People[100];
try{
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter(",");
while(inputFile.hasNext()){
// Store the data into array
}
inputFile.close();
}catch (FileNotFoundException e){
System.out.println("Check file");
}
}
}
Maybee smth like this:
public static People[] readPeople(File file) {
List<People> people = new ArrayList<>(100);
try (Scanner inputFile = new Scanner(file)) {
inputFile.useDelimiter(",");
while (inputFile.hasNext()) {
People obj = new People();
// e.g. line is equals to John,Done
// obj.setFirstName(inputFile.next());
// obj.setLastName(inputFile.next());
people.add(obj);
}
} catch(FileNotFoundException e) {
System.out.println("Check file");
}
return people.toArray(new People[people.size()]);
}
Related
I am trying to read a file and store the individual integers, but make the first integer in the file into a String. I have been able to read the file but I am struggling to store the integers respectively. I want to use them within the program.
The file has three integers per line separated by a whitespace.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class arrayListStuffs2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the file name: e.g \'test.txt\'");
String fileName = sc.nextLine();
try {
sc = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<String> listS = new ArrayList<>();
List<Integer> listI = new ArrayList<>();
while (sc.hasNextLine()) {
listI.add(sc.nextInt());
}
System.out.println(listI);
}
}
You can use the following approach. Iterate lines, split it, take first as string and other two as integer (assuming that you have data as
1 2 3
4 5 6
7 8 9
):
List<String> listS = new ArrayList();
List<Integer> listI = new ArrayList();
// try with resource automatically close resources
try (BufferedReader reader = Files.newBufferedReader(Paths.get("res.txt")))
{
reader.lines().forEach(line -> {
String[] ints = line.split(" ");
listS.add(String.valueOf(ints[0]));
listI.add(Integer.parseInt(ints[1]));
listI.add(Integer.parseInt(ints[2]));
});
} catch (IOException e) {
e.printStackTrace();
}
Output is :
I'm new to Java and I have to read from a file, and then convert what I have read into variables. My file consists of a fruit, then a price and it has a long list of this. The file looks like this:
Bananas,4
Apples,5
Strawberry,8
...
Kiwi,3
So far I have created two variables(double price and String name), then set up a scanner that reads from the file.
public void read_file(){
try{
fruits = new Scanner(new File("fruits.txt"));
print_file();
}
catch(Exception e){
System.out.printf("Could not find file\n");
}
}
public void print_file(){
while(fruits.hasNextLine()){
String a = fruits.nextLine();
System.out.printf("%s\n", a);
return;
}
}
Currently I am only able to print out the entire line. But I was wondering how I could break this up to be able to store the lines into variables.
So your string a has an entire line like Apples,5. So try to split it by comma and store it into variables.
String arr[] = a.split(",");
String name = arr[0];
int number = Integer.parseInt(arr[1]);
Or if prices are not integers, then,
double number = Double.parseDouble(arr[1]);
Using java 8 stream and improved file reading capabilities you can do it as follows. it stores item and count as key value pair in a map. It is easy to access by key afterwards.
I know this Maybe too advance but eventually this will help you later when getting to know new stuff in java.
try (Stream<String> stream = Files.lines(Paths.get("src/test/resources/items.txt"))) {
Map<String, Integer> itemMap = stream.map(s -> s.split(","))
.collect(toMap(a -> a[0], a -> Integer.valueOf(a[1])));
System.out.println(itemMap);
} catch (IOException e) {
e.printStackTrace();
}
output
{Apples=5, Kiwi=3, Bananas=4, Strawberry=8}
You can specify a delimiter for the scanner by calling the useDelimiter method, like:
public static void main(String[] args) {
String str = "Bananas,4\n" + "Apples,5\n" + "Strawberry,8\n";
try (Scanner sc = new Scanner(str).useDelimiter(",|\n")) {
while (sc.hasNext()) {
String fruit = sc.next();
int price = sc.nextInt();
System.out.printf("%s,%d\n", fruit, price);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"C://Test/myfile.txt")); //Your file location
String line = reader.readLine(); //reading the line
while(line!=null){
if(line!=null && line.contains(",")){
String[] data = line.split(",");
System.out.println("Fruit:: "+data[0]+" Count:: "+Integer.parseInt(data[1]));
}
//going over to next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I need to make a system for storing customer information and all quotations to an external file as well as entering more customers, listing customers, and the same with the quotations. As well as this I need to link all quotations/customers to an ID. I basically need to do SQL in java. However, I really need help with my input and output system, and writing all info to an array. I have got two main pieces of code but they are very inefficient and I need some suggestions, improvements or an entirely different system.
Input from file Code:
import java.io.*; //import classes
import java.util.ArrayList;
import java.util.Iterator;
public class MyTextReader{
public static void main(String[] args){
String myDirectory = System.getProperty("user.dir");
String fullDirectory = myDirectory + "\\myText.txt";
String input_line = null;
ArrayList<String> textItems = new ArrayList<String>(); //create array list
try{
BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
while((input_line = re.readLine()) != null){
textItems.add(input_line); //add item to array list
}
}catch(Exception ex){
System.out.println("Error: " + ex);
}
Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
while(myIteration.hasNext()){ //while items exist
System.out.println(myIteration.next()); //print item to command-line
}
}
}
Output to File
import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
public static void main(String[] args){
FileWriter writeObj; //declare variables (uninstantiated)
PrintWriter printObj;
String myText = "Hello Text file";
try{ //risky behaviour – catch any errors
writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
printObj = new PrintWriter(writeObj);//create both objects
printObj.println(myText); //print to file
printObj.close(); //close stream
}catch(Exception ex){
System.out.println("Error: " + ex);
}
}
}
For reading text from a file
FileReader fr = new FileReader("YourFile.txt");
BufferedReader br = new BufferedReader(fr);
String s="";
s=br.readLine();
System.out.println(s);
For Writting Text to file
PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
writeText.println("The first line");
writeText.println("The second line");
writeText.close();
I have to write code that will reverse the order of the string and write it in a new file. For example :
Hi my name is Bob.
I am ten years old.
The reversed will be :
I am ten years old.
Hi my name is Bob.
This is what I have so far. Not sure what to write for the outWriter print statement. Any help will be appreciated. Thanks!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class FileRewinder {
public static void main(String[] args) {
File inputFile = new File("ascii.txt");
ArrayList<String> list1 = new ArrayList<String>();
Scanner inputScanner;
try {
inputScanner = new Scanner(inputFile);
} catch (FileNotFoundException f) {
System.out.println("File not found :" + f);
return;
}
while (inputScanner.hasNextLine()) {
String curLine = inputScanner .nextLine();
System.out.println(curLine );
}
inputScanner.close();
File outputFile = new File("hi.txt");
PrintWriter outWriter = null;
try {
outWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
System.out.println("File not found :" + e);
return;
}
outWriter.println(???);
outWriter.close();
}
}
My suggestion is read entire file first and store sentences(you can split by .) in a LinkedList<String>(this will keep insertion order)
Then use Iterator and get sentences in reverse order. and write them into a file. make sure to put . just after each sentence.
After System.out.println(curLine ); add list1.add(curline); that will place your lines of text into your list.
At the end create a loop over list1 backwards:
for(int i = list1.size() - 1 , i > 0, --i) {
outWriter.println(list1[i]);
}
If the file contains an amount of lines which can be loaded into the memory. You can read all lines into a list, reverse the order of the list and write the list back to the disk.
public class Reverse {
static final Charset FILE_ENCODING = StandardCharsets.UTF_8;
public static void main(String[] args) throws IOException {
List<String> inLines = Files.readAllLines(Paths.get("ascii.txt"), FILE_ENCODING);
Collections.reverse(inLines);
Files.write(Paths.get("hi.txt"), inLines, FILE_ENCODING);
}
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Cities {
public static void main(String[] args) throws IOException {
String filename;
System.out.println("Enter the file name : ");
Scanner kb = new Scanner(System.in);
filename = kb.next();
//Check if file exists
File f = new File(filename);
if(f.exists()){
//Read file
File myFile = new File(filename);
Scanner inputFile = new Scanner(myFile);
//Create arraylist object
ArrayList<String> list = new ArrayList<String>();
String cit;
while(inputFile.hasNext()){
cit = inputFile.toString();
list.add(inputFile.toString());
}
System.out.println(list);
}else{
System.out.println("File not found!");
}
}
}
I am trying to read a file and add the contents to an arraylist object (.txt file contains strings), but I am totally lost. Any advice?
You should read the file one line by one line and store it to the list.
Here is the code you should replace your while (inputFile.hasNext()):
Scanner input = null;
try
{
ArrayList<String> list = new ArrayList<String>();
input = new Scanner( new File("") );
while ( input.hasNext() )
list.add( input.nextLine() );
}
finally
{
if ( input != null )
input.close();
}
And you should close the Scanner after reading the file.
If you're using Java 7+, then you can use the Files#readAllLines() to do this task for you, instead of you writing a for or a while loop yourself to read the file line-by-line.
File f = new File(filename); // The file from which input is to be read.
ArrayList<String> list = null; // the list into which the lines are to be read
try {
list = Files.readAllLines(f.toPath(), Charset.defaultCharset());
} catch (IOException e) {
// Error, do something
}
You can do it in one single line with Guava.
final List<String> lines = Files.readLines(new File("path"), Charsets.UTF8);
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset)