I am trying to read from a text file, but whenever the program gets to my while loop it just skips over it. I used a previous example I had to check to see if I did it correctly, but it doesn't seem to be working this time.
EDIT: to clarify, the while with "b++" under it is being skipped.
EDIT 2: Updated code.
public static void main(String[] args) throws FileNotFoundException {
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
File file = new File("ToDoItems.txt");
Scanner ReadFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + "\n");
} else {
System.out.println("Here is the list so far:");
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
Ideally I want it to print a part of the Array each time it passes through the while loop. But it just ends up skipping over it.
I checked the text file itself, and it does have the information I want to print to it. Yet for some reason the scanner won't read it properly.
I guess your problem is that you are trying to read a file that you are currently using, try close the fout object before read it, something like this:
public static void main(String[] args){
File file = new File("ToDoItems.txt");
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(file)) {
// ^^ here
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + System.lineSeparator());
} else {
// Important line is here!
fout.close(); // <--- Close printwriter before read file
System.out.println("Here is the list so far:");
Scanner ReadFile = new Scanner(file);
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
String[] stringArray = new String[b]; is problematic as your int b = 0;.
Also, it seems like you do not know how large your array will even be. I would suggest you use an ArrayList instead. That way you will not need a counter, just add to the ArrayList.
It would be better to try and catch your FileNotFoundException instead of throwing at the main but I guess you know that your file will always be there.
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.
This is what I have to do:
Create a new copy of the TestFileWriter program called WriterDemo that takes input from the user and writes it into the output file. The program should continue writing lines (a loop may help) until the user supplies an empty line (no text) as their input. Hint: a while loop that has a termination condition that depends on the input string from the user is a good place to start...
The program should be accessed from the terminal and I can't figure out where to put the while loop without ruining the program. The code below is the unmodified version of TestFileWriter. I don't need the full code of WriterDemo, but just some advice on how to use it. An help is greatly appreciated.
import java.io.FileReader;
import java.io.FileWriter;
public class WriterDemo {
public static void main(String args[]){;
FileWriter fout;
FileReader fin;
String str;
int k;
if(args.length==0){
System.out.println("Use an argument in the command line");
System.exit(0);
}
try{
fout = new FileWriter("WrittingProbe.txt");
for(int i=0; i<args.length; i++){
fout.write(args[i]);
fout.write(' ');
}
fout.close();
fin= new FileReader("WrittingProbe.txt");
System.out.println("The file content is:");
while((k=fin.read()) !=-1)
System.out.println((char)k);
System.out.println();
fin.close();
fout = new FileWriter("WrittingProbe.txt", true);
str="\nAdded Text\n";
fout.write(str);
fout.close();
fin = new FileReader("WrittingProbe.txt");
System.out.println("\nNow the file content is:");
while((k=fin.read()) != -1)
System.out.print((char)k);
System.out.println();
fin.close();
}
catch(Exception e){
System.out.println("Exception: " + e);
}
}
}
try (FileWriter fileWriter = new FileWriter("G:\\test.txt")) {
Scanner scn = new Scanner(System.in);
while (true) {
String string = scn.nextLine();
if (string.equals("0")) {
break;
} else {
fileWriter.write(string+"\n");
}
}
}
Scanner scn = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list.add(scn.nextLine());
for(;!list.get(list.size()-1).equals("");){ //Loops until the last input is a blank line
list.add(scn.nextLine());
//Or, you can do it here, as you go, if you want
}
//Or here, all at once, using the list
How can I load .txt file into string array?
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
//Obviously, exception
int i = 0;
while (sc.hasNextLine()) {
morphBuffer[i] = sc.nextLine();
i++;
//Obviously, exception
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
There is an issue with array's length, because I don't know how long my array will be.
Of course i saw this question, but there is not an array of string. I need it, because I have to work with whole text, also with null strings.
How can I load a text file into string array?
Starting with Java 7, you can do it in a single line of code:
List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));
If you need your data in a string array rather than a List<String>, call toArray(new Strinf[0]) on the result of the readAllLines method:
String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);
Use List
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
List<String> mylist = new ArrayList<String>();
while (sc.hasNextLine()) {
mylist.add(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
You can use Collection ArrayList
while (sc.hasNextLine()) {
list.add(sc.nextLine());
i++;
//Obviously, exception
}
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
So, what am I trying to do is I get the info from a text file,
For example, 134567H;Gabriel;24/12/1994;67;78;89
Then I display only Admin number which is the first one but not the whole line in drop down list. So here are my codes :
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
sc.useDelimiter(";");
while(sc.hasNextLine()){
studentList.add(sc.nextLine());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
And this is how I populate the drop down list :
public void populate() {
String [] studentList ;
studentList = Question3ReadFile.readFile();
jComboBox_adminNo.removeAllItems();
for (String str : studentList) {
jComboBox_adminNo.addItem(str);
}
}
However, my problem now is the options in drop down list is showing the whole line from the text file. It is not showing the admin number only. I tried with useDelimiter already. Am I supposed to use that?
Any help would be appreciated. Thanks in advance.
Rince help check.
public class Question3ReadFile extends Question3 {
private String adminNo;
public Question3ReadFile(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
studentList.add(new Question3ReadFile(sc.nextLine()));
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
hasNext and next instead of hasNextLine and nextLine
public static void main(String[] args) {
String input = " For example, 134567H;Gabriel;24/12/1994;67;78;89";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(";");
String firstPart = null;
while(scanner.hasNext()){
firstPart = scanner.next();
break;
}
String secondPart = input.split(firstPart)[1].substring(1);
System.out.println(firstPart);
System.out.println(secondPart);
scanner.close();
}
Don't use delimiter in this case. I suggest to make a Student object out of the line.
studentList.add(new Student(sc.nextLine));
and have the Student class:
public class Student {
private final String adminNo;
public Student(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public String getAdminNo() {
return adminNo;
}
}
and then you just read the fields you need later (student.getAdminNo()) for example.
This approach is much prettier and easier to extend later.
upd: simplistic approach
Or don't bother with stupid OO and just do this:
studentList.add(sc.nextLine.split(";")[0]);
I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}