I'm working on a school assignment, the requirements are as follows: "Design a class that has a static method named writeArray. The method should take two arguments: the name of the file and a reference to an int array. The file should be opened as a binary file, the contents of the array should be written to the file, then the file should be closed. Write a second method in the class named readArray. The method should take two arguments: the name of a file, and a reference to an int array. The file should be opened, data should be read from the file and stored in the array, then the file should be closed. Demonstrate both methods in a program."
Here's my code so far for the class and demo:
import java.io.*;
public class FileArray
{
public static void writeArray(String filename, int[] array) throws IOException
{
//Open the file.
DataOutputStream outputFile = new DataOutputStream(new FileOutputStream("MyNumbers.txt"));
//Write the array.
for(int index = 0; index < array.length; index++)
{
outputFile.writeInt(array[index]);
}
//Close the file.
outputFile.close();
}
public static void readArray(String filename, int[] array) throws IOException
{
int number;
boolean endOfFile = false;
//Open the file.
FileInputStream fstream = new FileInputStream("MyNumbers.txt");
DataInputStream inputFile = new DataInputStream(fstream);
//Read values from the array.
while (!endOfFile)
{
try
{
number = inputFile.readInt();
}
catch (EOFException e)
{
endOfFile = true;
}
}
//Close the file.
inputFile.close();
}
}
Second class:
import java.io.*;
public class FileArrayDemo extends FileArray
{
public static void main(String[] args)
{
//Create arrays.
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
int[] test = new int[8];
//Try/catch clause.
try
{
//Write the contents of the numbers array to the file MyNumbers.txt.
FileArray fileArray = new FileArray();
fileArray.writeArray("MyNumbers.txt", numbers);
//Read the contents of the file MyNumbers.txt into the test array.
fileArray.readArray("MyNumbers.txt", test);
//Display the numbers from the test array.
System.out.println("The numbers read from the file are:");
for (int i = 0; i < test.length; i++)
System.out.print(test[i] + " ");
}
catch (IOException e)
{
System.out.println("Error = " + e.getMessage());
}
}
}
When I try to use the demo file, my array is showing all 0's instead of numbers 1-8. I'm not sure what I'm doing wrong here at all. I've been following along with the examples from my book, but they only provide demonstrations in one class instead of having a class that creates methods to perform the write/read operations.
You need just to modify the array passed in parameters, your readArray function is just read and does not modify the array.
try ramplacing your readArray function by this one:
public static void readArray(String filename, int[] array) throws IOException{
int number;
boolean endOfFile = false;
//Open the file.
FileInputStream fstream = new FileInputStream("MyNumbers.txt");
DataInputStream inputFile = new DataInputStream(fstream);
//Read values from the array.
int i = 0;
while (!endOfFile){
try{
number = inputFile.readInt();
array[i] = number;
i++;
}catch (EOFException e)
{
endOfFile = true;
}
}
//Close the file.
inputFile.close();
}
result :
The numbers read from the file are:
1 2 3 4 5 6 7 8
Related
Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.
I am trying to take an initial CSV file, pass it through a class that checks another file if it has an A or a D to then adds or deletes the associative entry to an array object.
example of pokemon.csv:
1, Bulbasaur
2, Ivysaur
3, venasaur
example of changeList.csv:
A, Charizard
A, Suirtle
D, 2
That being said, I am having a lot of trouble getting the content of my new array to a new CSV file. I have checked to see whether or not my array and class files are working properly. I have been trying and failing to take the final contents of "pokedex1" object array into the new CSV file.
Main File
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class PokedexManager {
public static void printArray(String[] array) {
System.out.print("Contents of array: ");
for(int i = 0; i < array.length; i++) {
if(i == array.length - 1) {
System.out.print(array[i]);
}else {
System.out.print(array[i] + ",");
}
}
System.out.println();
}
public static void main(String[] args) {
try {
//output for pokedex1 using PokemonNoGaps class
PokemonNoGaps pokedex1 = new PokemonNoGaps();
//initializes scanner to read from csv file
String pokedexFilename = "pokedex.csv";
File pokedexFile = new File(pokedexFilename);
Scanner pokescanner = new Scanner(pokedexFile);
//reads csv file, parses it into an array, and then adds new pokemon objects to Pokemon class
while(pokescanner.hasNextLine()) {
String pokeLine = pokescanner.nextLine();
String[] pokemonStringArray = pokeLine.split(", ");
int id = Integer.parseInt(pokemonStringArray[0]);
String name = pokemonStringArray[1];
Pokemon apokemon = new Pokemon(id, name);
pokedex1.add(apokemon);
}
//opens changeList.csv file to add or delete entries from Pokemon class
String changeListfilename = "changeList.csv";
File changeListFile = new File(changeListfilename);
Scanner changeScanner = new Scanner(changeListFile);
//loads text from csv file to be parsed to PokemonNoGaps class
while(changeScanner.hasNextLine()) {
String changeLine = changeScanner.nextLine();
String[] changeStringArray = changeLine.split(", ");
String action = changeStringArray[0];
String nameOrId = changeStringArray[1];
//if changList.csv file line has an "A" in the first spot add this entry to somePokemon
if(action.equals("A")) {
int newId = pokedex1.getNewId();
String name = nameOrId;
Pokemon somePokemon = new Pokemon(newId, name);
pokedex1.add(somePokemon);
}
//if it has a "D" then send it to PokemonNoGaps class to delete the entry from the array
else { //"D"
int someId = Integer.parseInt(nameOrId);
pokedex1.deleteById(someId);
}
//tests the action being taken and the update to the array
//System.out.println(action + "\t" + nameOrId + "\n");
System.out.println(pokedex1);
//*(supposedly)* prints the resulting contents of the array to a new csv file
String[] pokemonList = changeStringArray;
try {
String outputFile1 = "pokedex1.csv";
FileWriter writer1 = new FileWriter(outputFile1);
writer1.write(String.valueOf(pokemonList));
} catch (IOException e) {
System.out.println("\nError writing to Pokedex1.csv!");
e.printStackTrace();
}
}
//tests final contents of array after being passed through PokemonNoGaps class
//System.out.println(pokedex1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
PokemonNoGaps class file:
public class PokemonNoGaps implements ChangePokedex {
private Pokemon[] pokedex = new Pokemon[1];
private int numElements = 0;
private static int id = 0;
// add, delete, search
#Override
public void add(Pokemon apokemon) {
// if you have space
this.pokedex[this.numElements] = apokemon;
this.numElements++;
// if you don't have space
if(this.numElements == pokedex.length) {
Pokemon[] newPokedex = new Pokemon[ this.numElements * 2]; // create new array
for(int i = 0; i < pokedex.length; i++) { // transfer all elements from array into bigger array
newPokedex[i] = pokedex[i];
}
this.pokedex = newPokedex;
}
this.id++;
}
public int getNewId() {
return this.id + 1;
}
#Override
public void deleteById(int id) {
for(int i = 0; i < numElements; i++) {
if(pokedex[i].getId() == id) {
for(int j = i+1; j < pokedex.length; j++) {
pokedex[j-1] = pokedex[j];
}
numElements--;
pokedex[numElements] = null;
}
}
}
public Pokemon getFirstElement() {
return pokedex[0];
}
public int getNumElements() {
return numElements;
}
public String toString() {
String result = "";
for(int i = 0; i < this.numElements; i++) {
result += this.pokedex[i].toString() + "\n";
}
return result;
}
}
Excpeted output:
1, Bulbasaur
3, Venasaur
4, Charizard
5, Squirtle
Am i using the wrong file writer? Am I calling the file writer at the wrong time or incorrectly? In other words, I do not know why my output file is empty and not being loaded with the contents of my array. Can anybody help me out?
I spotted a few issues whilst running this. As mentioned in previous answer you want to set file append to true in the section of code that writes to the new pokedx1.csv
try {
String outputFile1 = "pokedex1.csv";
FileWriter fileWriter = new FileWriter(prefix+outputFile1, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
for(String pokemon : pokedex1.toString().split("\n")) {
System.out.println(pokemon);
bw.write(pokemon);
}
bw.flush();
bw.close();
} catch (IOException e) {
System.out.println("\nError writing to Pokedex1.csv!");
e.printStackTrace();
}
I opted to use buffered reader for the solution. Another issue I found is that your reading pokedex.csv but the file is named pokemon.csv.
String pokedexFilename = "pokemon.csv";
I made the above change to fix this issue.
On a side note I noticed that you create several scanners to read the two files. With these types of resources its good practice to call the close method once you have finished using them; as shown below.
Scanner pokescanner = new Scanner(pokedexFile);
// Use scanner code here
// Once finished with scanner
pokescanner.close();
String outputFile1 = "pokedex1.csv";
FileWriter writer1 = new FileWriter(outputFile1);
appears to be within your while loop so a new file will be created every time.
Either use the FileWriter(File file, boolean append) constructor or create before the loop
I have a bunch of code that has now evolved into a fully functioning console based (mostly) game. I'm now curious that if I want to implement an Input/Output function do I have to create it in a different file or can I put it in the same class as my code. For instance, an example my lecturer has given for writing a fileIO for saving names is the following:
import java.io.*;
class savenames
{
public static void main(String[] params) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("mydata.txt"));
// Create an array with some sample names to store
String [] names = {"Paul", "Jo", "Mo"};
// Store the names from the array in the file, one name per line
for (int i = 0; i < names.length; i++)
{
outputStream.println(names[i]);
}
outputStream.close();
System.exit(0);
}
}
This accompanies the following code (in a different file):
import java.io.*;
class readnames
{
public static void main(String[] params) throws IOException
{
BufferedReader inStream = new BufferedReader(new FileReader("mydata.txt"));
String [] names = new String[3];
System.out.println("The names in the file mydata.txt are:");
for (int i = 0; i < names.length; i++)
{
names[i] = inStream.readLine();
System.out.println(names[i]);
}
inStream.close();
System.exit(0);
}
}
I was just wondering if it would be possible do the two things in the same file, as my code has many different methods and I'm not sure how to make a separate method to do this. Thanks.
EDIT: Perhaps I can modify this question to make it a little better.
I have the following main method in my boardgame:
class newminip
{
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
System.exit(0);
}
.... insert code here ....
public static void exitmethod(int[] scorep1)
{
sort(scorep1);
for (int i = 0; i < 4; i++)
{
System.out.println("Player " + (i+1) + " scored " + scorep1[i] + "");
}
System.exit(0);
}
} //END class
And I want something that will save the scores into a new text file. I hope this had made it a tiny bit clearer.
Yes you could do it in one file. I have created a new class for it:
import java.io.*;
import java.util.ArrayList;
public class FileIO {
public static String[] readStringsFromFile(final String filename) throws IOException {
BufferedReader inStream = new BufferedReader(new FileReader(filename));
//Use ArrayList since you don't know how many lines there are in the file
ArrayList<String> lines = new ArrayList<String>();
String line;
//Read until you reach the end of the file
while ((line = inStream.readLine()) != null) {
lines.add(line);
}
inStream.close();
//Convert it back to a string array
return lines.toArray(new String[lines.size()]);
}
public static void writeStringsToFile(String[] lines, final String filename) throws IOException {
PrintWriter outputStream = new PrintWriter(new FileWriter(filename));
for (int i = 0; i < lines.length; i++) {
outputStream.println(lines[i]);
}
outputStream.close();
}
public static void main(String[] args) {
//To test the methods:
//Create an array to write to the file
String[] linesToWrite = {"firstLine", "secondLine", "thirdLine"};
try {
//Write the strings to a file named "testfile.txt"
writeStringsToFile(linesToWrite, "testfile.txt");
//Read all lines of a file named "testfile.txt"
String[] readLines = readStringsFromFile("testfile.txt");
//Print out the read lines
for (String line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error msg");
}
}
}
The main method in this case is just to test, you can remove it and copy the two other methods to your class. This is probably not the best or most efficient way to do file io but in your case this should do the job (:
EDIT:
So if you just need to read an write integers to a file you could use something like this:
import java.io.*;
import java.util.ArrayList;
public class FileIO {
public static Integer[] readIntegersFromFile(final String filename) throws IOException {
BufferedReader inStream = new BufferedReader(new FileReader(filename));
//Use ArrayList since you don't know how many lines there are in the file
ArrayList<Integer> integers = new ArrayList<Integer>();
String line;
//Read until you reach the end of the file
while ((line = inStream.readLine()) != null) {
//Parse integers form read string values
integers.add(Integer.parseInt(line));
}
inStream.close();
return integers.toArray(new Integer[integers.size()]);
}
public static void writeIntegersToFile(Integer[] lines, final String filename) throws IOException {
PrintWriter outputStream = new PrintWriter(new FileWriter(filename));
for (int i = 0; i < lines.length; i++) {
outputStream.println(lines[i]);
}
outputStream.close();
}
public static void main(String[] args) {
//To test the methods:
//Create an array to write to the file
Integer[] linesToWrite = {1, 100, 15};
try {
//Write the strings to a file named "testfile.txt"
writeStringsToFile(linesToWrite, "testfile.txt");
//Read all lines of a file named "testfile.txt"
Integer[] readLines = readStringsFromFile("testfile.txt");
//Print out the read lines
for (int line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error msg");
}
}
}
You can create a Java file with the code from both main methods and remove the System.exit(0); as you don't need it. This way one program will do both. I suggest you write the file before attempting to read it.
Putting it all in one program make the use of the file rather redundant however, in which case you can just print the array.
I have a text file of names( last and first). I have successfully been able to use RandomAccessFile class to load all the names into an Array of strings. What is left for me to do, is to assign each of the first names to an Array of first names and each of the last names in the list to an array of Last Names. Here is what I did but Im not getting any desired result.
public static void main(String[] args) {
String fname = "src\\workshop7\\customers.txt";
String s;
String[] Name;
String[] lastName, firstName;
String last, first;
RandomAccessFile f;
try {
f = new RandomAccessFile(fname, "r");
while ((s = f.readLine()) != null) {
Name = s.split("\\s");
System.out.println(Arrays.toString(Name));
for (int i = 0; i < Name.length; i++) {
first = Name[0];
last = Name[1];
System.out.println("last Name: " + last + "First Name: "+ first);
}
}
f.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Please help me out I seem to be confused on what kind of collection to use and how to go about it Thanks
You could create a method to read a file and put the data in an Array, but, if you are determined to use an Array you are going to have to create it at a fixed size b/c arrays are immutable in java
public class tmp {
public static void main(String[] args) throws FileNotFoundException {
//problem you have to create an array of fixed size
String[] array = new String[4];
readLines(array);
}
public static String[] readLines(String[] lines) throws FileNotFoundException {
//this counter can be printed to check the size of your array
int count = 0; // number of array elements with data
// Create a File class object linked to the name of the file to read
java.io.File myFile = new java.io.File("path/to/file.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(myFile);
/* This while loop reads lines of text into an array. it uses a Scanner class
* boolean function hasNextLine() to see if there another line in the file.
*/
while (infile.hasNextLine()) {
// read a line and put it in an array element
lines[count] = infile.nextLine();
count++; // increment the number of array elements with data
} // end while
infile.close();
return lines;
}
}
However, the preferred method is to use an ArrayList which is an object that uses dynamically resizing arrays as data is added. In other words, you don't need to worry about having different size text files.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
String str;
ArrayList<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
A little about random access.
Classes like BufferedReader and FileInputStream use a sequential process of reading or writing data. RandomAccess, on the other hand, does exactly as the name implies, which is to permit non-sequential, random access to the contents of a file. However, Random access is typically used for other applications like reading and writing to zip files. Unless you have speed concerns I would recommend using the other classes.
public static void main(String[] args) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
String str;
String names[];
List<String> firstName = new ArrayList();
List<String> lastName = new ArrayList();
try {
while ((str = in.readLine()) != null) {
names = str.split("\\s");
int count = 0;
do{
firstName.add(names[count]);
lastName.add(names[count+1]);
count = count + 2;
}while(count < names.length);
}
} catch (IOException e) {
e.printStackTrace();
}
// do whatever with firstName list here
System.out.println(firstName);
// do whatever with LastName list here
System.out.println(lastName);
}
I have a super beginner's question. I have a computer science test today and one of the practice problems is this:
Write a program that carries out the following tasks:
Open a file with the name hello.txt.
Store the message “Hello, World!” in the file.
Close the file.
Open the same file again.
Read the message into a string variable and print it.
This is the code I have for it so far:
import java.util.*;
import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y));
}
in.close();
out.close();
}
}
What's wrong with this code?
1) You need to close the stream
2) You need to refer to the x Arraylist with (y-1) otherwise you will get
a java.lang.IndexOutOfBoundsException . The indexes starts from 0 and not from 1.
http://www.tutorialspoint.com/java/util/arraylist_get.htm
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
out.close();
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
in.close();
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y-1));
}
}
}
I guess what's wrong with the code ist that you cant read anything from the file.
this is because PrintWriter is buffered
fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You need to close the file you have just writen to before openning it for reading so that the changes are fluched to the physical storage. Thus moving out.close(); right after out.println("Hello, World");
class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object
FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done
FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}