Hello there stackoverflow .
The thing im tring to make work is saving some information from an array to a file and then reading it back to another array . The goal is to save themes (hex color codes of user) so they can share their theme or backing it up .
Here is my code to write the array to file
String filename = "my.theme";
String[] numbers = new String[] {"1, 2, 3"};
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
for (String s : numbers) {
outputStream.write(s.getBytes());
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
The output is a file with :
1,2,3
Now how can i read it back to another array ?
For my goal . Can you suggest anything other then using this method ? Its ok to save as a xml too . Thanks :)
You can use a Scanner class, this small example will help you get started:
String input = "1,2,3";
Scanner scn = new Scanner(input); // Scanner also accepts a file!
scn.useDelimiter(","); // Since the integers are "comma" separated.
while(scn.hasNext())
{
System.out.println(scn.nextInt()); // here you can store your integers back into your array
}
scn.close();
OUTPUT:
1
2
3
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
Trying to save arraylist items to a text file, I kind of have it working but it saves the whole arraylist on one line
I am hoping to save it per line and not have any duplicates or the empty brackets at the start, Any help would be much appreciated. Also if possible to remove the brackets around the text for easier reading into an arraylist
FileOutputStream is more fitting for when your data is already in a byte format. I suggest you use something like a PrintWriter.
PrintWriter pw = null;
try {
File file = new File("file.txt"); //edited
pw = new PrintWriter(file); //edited
for(String item: Subreddit_Array_List)
pw.println(item);
} catch (IOException e) {
e.printStackTrace();
}
finally{
pw.close();
}
Keep in mind this overwrites what was in the file before rather than appends to it. The output will be formatted like:
Cats
Dogs
Birds
You can iterate over the map and save all variables in separate lines.
Example:
private List<Object> objects;
private void example() {
//JDK >= 8
this.objects.forEach(this::writeInFile);
//JDK < 8
for (Object object : this.objects) {
this.writeInFile(object);
}
}
private void writeInFile(Object object) {
//your code here
}
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.
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();
}
}
I have a file that contains data like:
Fantasy Football
Peyton Manning; 49
Eli Manning; 34
Colin Kaepernick; 33
I have read in the file using a Scanner, now I want to go through the data and pass it to this class.
class GBar {
String text;
int value;
GBar(String t, int v) {
text = t;
value = v;
}
}
I'm not sure how to pass the relevant info from the file to GBar.
Here is my code to read in the file
void ReadIn(String filename) {
Scanner s = null;
try {
FileInputStream fileInputStream = new FileInputStream(filename);
s = new Scanner(fileInputStream);
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
while (s.hasNextLine()) {
String line = s.nextLine();
fileDataArray.add(line);
}
s.close();
}
You've got a good start. What you have done so far is to set up a way to read the file. You haven't actually read the lines in the file yet. After you create the Scanner, you need to loop until there are no more lines left. Check the Scanner Javadoc for hints on how to do that. Then you can either process each line as you read it or store them off and process them in bulk once you've read them all. To process them you probably want to split the lines you get from the Scanner on the ; character.