How to read from textfile and pass values to another class Java? - java

I'm making a Java program that needs to read info from a text file and then store it in an array and pass it to another class when called. My issue is that I can't seem to call it due to the IOException needed in the file reader class.
This is the main class that is supposed to call the fileReader.
public class window {
public static void main(String[] args){
String[] people = readFromText.read("people.txt");
}
}
File Reader Class
public class readFromText{
public static String[] read(String textFile) throws IOException {
BufferedReader inputFile = new BufferedReader(new
FileReader(textFile));
String[] array = new String[10];
String line = inputFile.readLine().toString();
int cnt = 0;
while (line!=null){
array[cnt] = line;
line = inputFile.readLine().toString();
cnt++;
}
inputFile.close();
return array;
}
}
Is it possible to do this, this way?

Firstly your code is not correct. You can not return the String[] array for the function need String[][].
Secondly for problem about exception you just need to catch it in your main class.
try {
String[] people = readFromText.read("people.txt");
} catch (IOException e) {
e.printStackTrace();
}

Related

While using a boolean method, how do I add the String contents of a txt file into an array list

I am attempting to use the method "public boolean readArtists" with a scanner to read strings from a file and return true if opened successfully. This method is also supposed to "Adds to the list all of the artists stored in the file passed parameter."
I've seen how to write the code in a public static void method that will read the text file and return it:
public static void main(String[] args) {
File file = new File("artists30.txt");
String content = null;
try {
try (Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name())) {
content = scanner.useDelimiter("\\A").next();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
}
Here is the test:
I have to keep the method "public boolean readArtists(String filename), so my question is, within this method, how do I read the contents of the text file into an ArrayList using a scanner, while also returning true if the file is opened successfully, Otherwise, handling the exception, displaying an appropriate error message containing the name of the missing file and return false.
public class Artists{
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("filename goes here"));
System.out.println(artists);
}
public Artists(String artist, String genre)
{
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if(file.createNewFile()) {
System.out.println("err "+fileName);
return false;
}
sc = new Scanner(file);
while(sc.hasNextLine()) {
artists.add(sc.nextLine());
}
}catch(Exception e) {
e.printStackTrace();
}
if(sc!=null) {sc.close();}
return true;
}
}
This answer reads data from a .txt document into an ArrayList, as long as the .txt document names are on seperate lines in the document. It also outputs err \FILE\NAME and returns false if the document does not exist and true if it does. https://www.w3schools.com/java/java_files.asp is a great website to learn java by the way and this link brings you to the file handling page.
You can achieve that using,
public static void main(String[] args) throws FileNotFoundException {
String filepath = "C:\\Users\\Admin\\Downloads\\testFile.txt";
List<String> arrayList = new ArrayList<>();
if(readArtists(filepath)) {
Scanner sc = new Scanner(new File(filepath));
sc.useDelimiter("\\A");
while(sc.hasNext()) {
arrayList.add(sc.next());
}
}
System.out.println(arrayList);
}
public static boolean readArtists(String filename)
{
File file = new File(filename); //full path of the file with name
return file.canRead();
}

Pass in file text into hashmap

I am having a bit of an issues trying to pass in a file read by my program and sorted accordantly. I am not used to working with files, and i ran out of ideas as to how this could be achieved.
/////////////////////////////////////// class reads file ///////////////////////////////////
import java.io.*;
public class InFileReader {
private BufferedReader inputStream = null;
private String fileLine;
private StringBuilder sb;
public String getFile(File fileRead) throws FileNotFoundException,
IOException {
inputStream = new BufferedReader(new FileReader(fileRead)); //reads files
sb = new StringBuilder();
while((fileLine = inputStream.readLine()) != null){//keep reading lines in file till there is none
sb.append(fileLine).append("\n");
}
return sb.toString(); //returns StringBuffer read values in String form
}
}
///////////////////////////////////////////////////// end of read file class ///////////////////////
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
try {
String input = fileReader.getFile(fileRead.getAbsoluteFile());
HashMap<Integer, Thing.Ship> hashmap = new HashMap<>();
while (!input.isEmpty()) { // as long as there is data in the file keep looping
Scanner sc = new Scanner(input); // scan file
if (!input.startsWith("//")) { // take out "//" from directory
String type = "";
if (sc.hasNext()) { // if there are character lines get next line
type = sc.next();
}
if (type.equalsIgnoreCase("port")) { // looks for "port"
world.assignPort(new Thing.SeaPort(sc)); // assigns value to Seaport
} else if (type.equalsIgnoreCase("dock")) {
world.assignDock(new Thing.Dock(sc));
} else if (type.equalsIgnoreCase("ship")) {
Thing.Ship s = new Thing.Ship(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("pship")) {
Thing.Ship s = new Thing.PassengerShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("cship")) {
Thing.Ship s = new Thing.CargoShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("person")) {
world.assignPerson(new Thing.Person(sc));
}
}
}
//inputOut.setText(type);
inputOut.setText(world.toString());
} catch (Exception e) {
System.out.println(e + "-----");
}
}
Here fileRead knows where to find the file to be read "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt"
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
this is where things just fall apart:
String input = fileReader.getFile(fileRead.getAbsoluteFile());
My intent here is to pass the location of the file so that the getFile class can read it and then be sorted into the hashmap.
again i am not familiar with how to work with file, any suggestion or comment would be greatly appreciated.
thank you in advanced.
If you get a FileNotFoundException then the file was not found.
You say the filename was "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt".
If you type that name in the code you must escape the backslash:
"C:\\Users\\abe\\IdeaProjects\\CreateSeaPortDataFile\\src\\text.txt".

ArrayList different method's scope

I have a problem with the code below. I'm getting different results base on where the line list = new ArrayList<InClass>(); is declared. In place //B but everything works fine when I add it to //A and I cannot understand the difference. Here is the code:
import java.util.*;
import java.io.*;
public class ArrayListOne {
private ArrayList<InClass> list;
private InClass in;
public static void main(String args[]) {
ArrayListOne a = new ArrayListOne();
a.readFile();
}
public void readFile() {
//A
/**
* adding "list = new ArrayList<InClass>();"
* getting all 4 lines of test.txt
*/
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
assignToObject(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
public void assignToObject(String s) {
//B
/**
* adding "list = new ArrayList<InClass>();"
* getting just last line of test.txt
*/
InClass n = new InClass(s);
list.add(n);
System.out.println(list.size());
}
public void readObject() {
for (int i=0; i<list.size(); i++) {
in = list.get(i);
System.out.println(in.stTest);
}
}
//inner class
public class InClass {
String stTest;
public InClass(String s) {
stTest = s;
}
}
}
the test.txt has 3 lines. in //A, I'm getting all three lines (what I want) but in //B I just get the last line.
It's easier to see the difference if you "inline" assignToObject() by copy-pasting the contents of assignToObject() to the proper place in readFile():
public void readFile() {
// B
// list = new ArrayList<InClass>();
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
// Here is where assignToObject() was //
// B
// list = new ArrayList<InClass>();
InClass n = new InClass(line);
list.add(n);
System.out.println(list.size());
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
Now think about if you put list = new ArrayList<InClass>() in A and B.
If you declare list = new ArrayList<InClass>() at A (i.e. inside readFile()), the statement will be executed once -- when readFile() is called in main(). So you'll end up with one ArrayList containing everything you need.
However, if you declare list = new ArrayList<InClass>() at B (i.e. inside assignToObject()), you'll get a new list for every line you read (i.e. every time you call assignToObject()). This means that every iteration you'll end up with a new ArrayList that only contains the most recently read line. The ArrayList containing the previous line was thrown away, as the reference that used to point to it now points to a new object.

ArrayList saved to textfile

I want to save the contents of my arraylist to a textfile. What I have so far is shown below, however instead of adding x.format("%s%s", "100", "control1"); to the textfile, I want to add objects from an arraylist, how do I go about this?
import java.util.*;
public class createfile
{
ArrayList<String> control = new ArrayList<String>();
private Formatter x;
public void openFile()
{
try {
x = new Formatter("ControlLog.txt");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: Your file has not been created");
}
}
public void addRecords()
{
x.format("%s%s", "100", "control1");
}
public void closeFile()
{
x.close();
}
}
public class complete
{
public static void main(String[] args)
{
createfile g = new createfile();
g.openFile();
g.addRecords();
g.closeFile();
}
}
Both ArrayList and String implement Serializable. Since you have an ArrayList of string you can write it to the file like this:
FileOutputStream fos = new FileOutputStream("path/to/file");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(myArrayList); //Where my array list is the one you created
out.close();
Here is a really good tutorial that shows you how to write java objects to a file.
The written objects can be read back from the file in a similar way.
FileInputStream in = new FileInputStream("path/to/file");
ObjectInputStream is = new ObjectInputStream(in);
myArrayList = (ArrayList<String>) is.readObject(); //Note that you will get an unchecked warning here
is.close()
Here is a tutorial on how to read objects back from a file.

NullPointerException Error in program that writes to file

I am trying to print strings into a file. What have I done wrong and it always gives me a NullPointException? I believe my exceptions catch something or an argument is needed and I dont enter it. But where?
I have writen this code, that contains the main function.
EDIT: Getting error in the second line from the bottom some.items[0]="Testing One!";.
import java.io.*;
public class StringPrinter {
public String[] items;
public File file;
public StringPrinter(String fileName){
file = new File(fileName);}
public void toFile(){
try{
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st:items){
pw.println(st);
}
}
catch(Exception exception){}
}
public static void main(String args[]){
StringPrinter some=new StringPrinter("Workyou.txt");
some.items[0]="Testing One!";
some.items[1]="Testing Two!";
some.toFile();
}
}
It seems you are getting Exception here
some.items[0]="Testing One!";
this is because you did not initialize
public String[] items;
initialize it something like this in your constructor
public StringPrinter(String fileName){
file = new File(fileName);
items = new String[SIZE];
}
first : As all said you have to initialize the array.
Second : Why not print data to file
Solution :
In method ToFile()
after the for loop printing the string[] value, you need to close the Printer Writer
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st:items){
pw.println(st);
}
**pw.close()**
It will print your data to file.
You're trying to set the string Testing One! to the first position of the array items, but you did not initialize that string array
some.items[0]="Testing One!";
If you change this line.
public String[] items;
to this one
public String[] items = new String[2];
then it will work. Notice that you must predefine the size of the array. Notice that the array size is fixed. If you don't want the array size to be fixed, I suggest you use the wrapper class ArrayList, which size can be expanded.
import java.io.*;
import java.util.ArrayList;
public class StringPrinter {
public ArrayList<String> items = new ArrayList<String>();
public File file;
public StringPrinter(String filename) {
file = new File(filename);
}
public void toFile() {
try {
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st : items) {
pw.println(st);
}
pw.close();
}
catch(Exception exception) { }
}
public static void main(String args[]) {
StringPrinter some = new StringPrinter("Workyou.txt");
some.items.add("Testing One!");
some.items.add("Testing Two!");
some.toFile();
}
}
The items array is not initialized. You got to initialize it before actually assigning some values. If you do not want to create a fixed size classical array then you can try to use ArrayList.
Try this, the complete solved code:
import java.io.*;
public class StringPrinter {
public String[] items;
public File file;
public StringPrinter(String filename) {
file = new File(filename);
}
public void toFile() {
try {
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st : items){
pw.println(st);
}
pw.close(); //needed to close the writer stream to write data in file
}
catch(Exception exception) {}
}
public static void main(String args[]) {
StringPrinter some = new StringPrinter("Workyou.txt");
some.items = new String[2]; //needed to initialize array with size
some.items[0]="Testing One!";
some.items[1]="Testing Two!";
some.toFile();
}
}
Try with this , this should print the text in a file
public class StringPrinter {
public String[] items = new String [2];
public File file;
public StringPrinter(String fileName){
file = new File(fileName);}
public void toFile(){
try{
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st:items){
pw.print(st);
pw.flush();
}
}
catch(Exception exception){}
}
public static void main(String args[]){
StringPrinter some=new StringPrinter("Workyou.txt");
some.items[0]="Testing One!";
some.items[1]="Testing Two!";
some.toFile();
}
}
Documentation for flush . Not required to close the writers compulsorily to see the content in a file , just calling the flush to the writer it will add the content to the files.

Categories

Resources