I already read data from a text file (in the file there are all numbers (int and double)) and in my class, I have an array of an object type. I have no idea how to put data which read from the txt file into the array.
I would greatly appreciate it if you can give me some answers.
this.object=new Object[nums1];
File file=new File("/homes/xx.txt");
try {
Scanner scnr=new Scanner(file);
int lineNumber= 1;
while (scnr.hasNextLine()) {
String line = scnr.nextLine();
System.out.println(line);
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
A couple of sample lines from my input file:
3
1.0 2.5 3.0
I think I need to distinguish between whole numbers and numbers with a decimal point. Should I create another object type so I can store int and double separately?
try this:
File file=new File("/homes/xx.txt");
try {
Scanner scnr=new Scanner(file);
List<String> lines = new ArrayList<String>();
while (scnr.hasNextLine()) {
lines.add(scnr.nextLine());
System.out.println(lines);
}
String[] arr = lines.toArray(new String[0]);
}
catch (FileNotFoundException e) {
System.out.println(e);
If you have a space between your integers and doubles, try this:
Object []objects = file;
Object []numbers = objects.split(β β);
I am not sure about Object []objects = file; part because I am new java learner too. But if you can insert whole text to an array, you can split and assign values one by one with .split command to another array.
Related
my CSV file is called " Noteslist" it looks like this in principle, but the list goes down for more than 50 rows
MatrNr,Note
584711,40
584712,55
584713,67
584714,23
584715,89
584716,95
584717,59
584718,66
584719,81
584720,78
584721,97
584722,11
584723,17
584724,68
584725,45
i am supposed to read the CSV file and store the values into a 2 dimensional Int array. i did the first part reading the csv file, but i don't know about the second part, i really would appreciate your help.
my code so far :
public static void main(String[] args){
String fileName= "Noteslist.csv";
File file=new File(fileName);
try {
Scanner inputStream= new Scanner(file);
while ( inputStream.hasNext()){
String notesList = inputStream.next();
String values[]=notesList.split(",");
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Reading csv data and storing in to collection object. Solution already given in the below post.
Please check it out.
https://stackoverflow.com/a/62171055/2648257
the practice question i got says that i need to
create a java code that reads in csv file with name and height.
to read a file you must get a file name from user as string.
then you must store contents of file into two arrays one for name (string) and height(real number).
You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).
then prompt the user for name you want height of. it should output the height for userinput.
example csv file is
chris,180
jess,161
james, 174
its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation
import.java.util.*;
private class StudentNameHeight
private void main (string [] args)
{
String filename;
Scanner sc = new scanner(system.in);
System.out.println("enter file name")
filename = sc.nextline();
readFile (filename);
}
private void readFile (String filename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
try
{
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
// ?
catch (IOException e)
{
if (fileStrm != null)
{
try {fileStrm.close(); } catch (IOException e2){}
}
System.out.println("error in processing" + e.getMessage());
}
}
im new to java so, any small tip or help would be great
thanks
You code looks messy. As far as I understand from your question, you are willing to read a CSV file containing two entities, one is name and another is height and store these two entities in two different data structures. I'm teaching you a simple way to accomplish this in below code snippet.
public void processCSVFile(String filePath){
try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
//Create two lists to hold name and height.
List<String> nameList = new ArrayList<>();
List<Integer> heightList = new ArrayList<>();
String eachLine = "";
/*
* Read until you hit end of file.
*/
while((eachLine = fileReader.readLine()) != null){
/*
* As it is CSV file, split each line at ","
*/
String[] nameAndHeightPair = eachLine.split(",");
/*
* Add each item into respective lists.
*/
nameList.add(nameAndHeightPair[0]);
heightList.add(Integer.parseInt(nameAndHeightPair[1]));
}
/*
* If you are very specific, you can convert these
* ArrayList to arrays here.
*/
}catch(IOException e1){
e1.printStackTrace();
}
}
For homework, we have to read in a txt file which contains a map. With the map we are supposed to read in its contents and place them into a two dimensional array.
I've managed to read the file into a one dimensional String ArrayList, but the problem I am having is with converting that into a two dimensional char array.
This is what I have so far in the constructor:
try{
Scanner file=new Scanner (new File(filename));
while(file.hasNextLine()){
ArrayList<String> lines= new ArrayList<String>();
String line= file.nextLine();
lines.add(line);
map=new char[lines.size()][];
}
}
catch (IOException e){
System.out.println("IOException");
}
When I print out the lines.size() it prints out 1 but when I look at the file it has 10.
Thanks in advance.
You have to create the list outside the loop. With your actual implementation, you create a new list for each new line, so it will always have size 1.
// ...
Scanner file = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // <- declare lines as List
while(file.hasNextLine()) {
// ...
BTW - I wouldn't name the char[][] variable map. A Map is a totally different data structure. This is an array, and if you create in inside the loop, then you may encounter the same problems like you have with the list. But now you should know a quick fix ;)
Change the code as following:
public static void main(String[] args) {
char[][] map = null;
try {
Scanner file = new Scanner(new File("textfile.txt"));
ArrayList<String> lines = new ArrayList<String>();
while (file.hasNextLine()) {
String line = file.nextLine();
lines.add(line);
}
map = new char[lines.size()][];
} catch (IOException e) {
System.out.println("IOException");
}
System.out.println(map.length);
}
I need to have this file print to an array, not to screen.And yes, I MUST use an array - School Project - I'm very new to java so any help is appreciated. Any ideas? thanks
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class HangmanProject
{
public static void main(String[] args) throws FileNotFoundException
{
String scoreKeeper; // to keep track of score
int guessesLeft; // to keep track of guesses remaining
String wordList[]; // array to store words
Scanner keyboard = new Scanner(System.in); // to read user's input
System.out.println("Welcome to Hangman Project!");
// Create a scanner to read the secret words file
Scanner wordScan = null;
try {
wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
while (wordScan.hasNext()) {
System.out.println(wordScan.next());
}
} finally {
if (wordScan != null) {
wordScan.close();
}
}
}
}
Nick, you just gave us the final piece of the puzzle. If you know the number of lines you will be reading, you can simply define an array of that length before you read the file
Something like...
String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
wordArray[index] = word;
index++;
Now that example's not going to mean much to be honest, so I did these two examples
The first one uses the concept suggested by Alex, which allows you to read an unknown number of lines from the file.
The only trip up is if the lines are separated by more the one line feed (ie there is a extra line between words)
public static void readUnknownWords() {
// Reference to the words file
File words = new File("Words.txt");
// Use a StringBuilder to buffer the content as it's read from the file
StringBuilder sb = new StringBuilder(128);
BufferedReader reader = null;
try {
// Create the reader. A File reader would be just as fine in this
// example, but hay ;)
reader = new BufferedReader(new FileReader(words));
// The read buffer to use to read data into
char[] buffer = new char[1024];
int bytesRead = -1;
// Read the file to we get to the end
while ((bytesRead = reader.read(buffer)) != -1) {
// Append the results to the string builder
sb.append(buffer, 0, bytesRead);
}
// Split the string builder into individal words by the line break
String[] wordArray = sb.toString().split("\n");
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
The second demonstrates how to read the words into an array of known length. This is probably closer to the what you actually want
public static void readKnownWords()
// This is just the same as the previous example, except we
// know in advance the number of lines we will be reading
File words = new File("Words.txt");
BufferedReader reader = null;
try {
// Create the word array of a known quantity
// The quantity value could be defined as a constant
// ie public static final int WORD_COUNT = 10;
String[] wordArray = new String[10];
reader = new BufferedReader(new FileReader(words));
// Instead of reading to a char buffer, we are
// going to take the easy route and read each line
// straight into a String
String text = null;
// The current array index
int index = 0;
// Read the file till we reach the end
// ps- my file had lots more words, so I put a limit
// in the loop to prevent index out of bounds exceptions
while ((text = reader.readLine()) != null && index < 10) {
wordArray[index] = text;
index++;
}
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
If you find either of these useful, I would appropriate it you would give me a small up-vote and check Alex's answer as correct, as it's his idea that I've adapted.
Now, if you're really paranoid about which line break to use, you can find the values used by the system via the System.getProperties().getProperty("line.separator") value.
Do you need more help with the reading the file, or getting the String to a parsed array? If you can read the file into a String, simply do:
String[] words = readString.split("\n");
That will split the string at each line break, so assuming this is your text file:
Word1
Word2
Word3
words will be: {word1, word2, word3}
If the words you are reading are stored in each line of the file, you can use the hasNextLine() and nextLine() to read the text one line at a time. Using the next() will also work, since you just need to throw one word in the array, but nextLine() is usually always preferred.
As for only using an array, you have two options:
You either declare a large array, the size of whom you are sure will never be less than the total amount of words;
You go through the file twice, the first time you read the amount of elements, then you initialize the array depending on that value and then, go through it a second time while adding the string as you go by.
It is usually recommended to use a dynamic collection such as an ArrayList(). You can then use the toArray() method to turnt he list into an array.
So far, I have 2 arrays: one with stock codes and one with a list of file names. What I want to do is input the .txt files from each of the file names from the second array and then split this input into: 1. Arrays for each file 2. Arrays for each part with each file.
I have this:
ImportFiles f1 = new ImportFiles("File");
for (String file : FileArray.filearray) {
if (debug) {
System.out.println(file);
}
try {
String line;
String fileext = "C:\\ASCIIpdbSKJ\\"+file+".txt";
importstart = new BufferedReader(new FileReader(fileext));
for (line = importstart.readLine(); line != null; line = importstart.readLine()) {
importarray.add (line);
if (debug){
System.out.println(importarray.size());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
importarray.add ("End")
This approach works to create a large array of all the files, will it be easier to change the input method to split it as it is coming in or split the large array I have?
At this point, the stock code array is irrelevant. Once I have split the arrays down I know where I will go from there.
Thanks.
Edit: I am aware that this code is incomplete in terms of { } but it is only printstreams and debugging missed off.
If you want to get a map with a filename and all its lines from all the files, here are relevant code parts:
Map<String, List<String>> fileLines = new HashMap<String, List<String>>();
for (String file : FileArray.filearray)
BufferedReader reader = new BufferedReader(new FileReader(fileext));
List<String> lines = new ArrayList<String>();
while ((line = reader.readLine()) != null){
lines.add(line);
}
fileLines.put(file, lines);
}