how to save information from a file in java - java

I am supoose to read a file lets say it has 3 lines:
2
Berlin 0 2 2 10000 300
Nilreb 0 2 2 10000 300
the first integer number shows how many names(lines) i have.
the 2nd and 3rd lines show information about two post offices.
them i am suppose to read each line and save the data.
I have to create post offices that they are names: Berlin and Nilreb.
Can anyone help me?
so far i have done this:
public static void read_files() throws IOException{
Scanner in = new Scanner(new File("offices")); //open and read the file
int num_of_lines = in.nextInt();
while(in.hasNext()){
String offices = in.nextLine();
}

To read files I recommend to you to use an ArrayList:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now in your ArrayList you will have all the lines of your file. So, now, you can go through all the post offices that you have with a for loop (I start in the index 1 because the first line it's the line of how many post offices are in the file, you won't need it with this method) and split them to get all the information about them. For example, in the position 0 of the array of Strings you will have the name of your post Office and in the rest of the positions (1,2,3,4...) the rest of your values stored in your file (one value by space in your line). Like this:
for(int i = 1; i < list.size(); i++)
{
String[] line = list.get(i).split(" ");
System.out.println("The name of this post office is " + line[0]);
}
EDIT: I saw now in a comment above that you want to create a class for each line. Then you can do (inside the for loop, instead of the System.out.println) the code that I put below (supossing that your class will be PostOffice):
PostOffice postOffice = new PostOffice(line[0],line[1],line[2],line[3],line[4],line[5]);
Note: If you don't understand something about my code please let me know.
I expect it will be helpful for you!

I think I figured it out: can u check if it is correct:
public static void read_files() throws IOException{
Scanner in = new Scanner(new File("offices"));
int num_of_lines = in.nextInt();
String[] office = new String[num_of_lines];
while(in.hasNext()){
for(int = 0; i < num_of_lines; i++){
office[i] = in.next();
}
List item

Related

Having problems scanning a String from a file in Java

I'm trying to scan a line of text from a .txt file, split it up into seven numbers, change two of the numbers, and then write the new numbers back into the .txt file. The code below works fine the first time, but seems to have issues with reading from the text file a second time for the new starting String. I've done very similar things multiple times and had no issues, so I'm really not sure why I'm having problems this time around. The code I currently have is:
public void addWin(int numGuesses) throws IOException {
FileWriter writer = new FileWriter(*filepath*);
Scanner scan = new Scanner(new File(*filepath*));
String temp = "0;0;0;0;0;0;0;";
if (scan.hasNextLine()) {
temp = scan.nextLine();
}
String[] statsArr = temp.split(";");
scan.close();
statsArr[0] = Integer.toString(Integer.parseInt(statsArr[0]) + 1);
statsArr[numGuesses] = Integer.toString(Integer.parseInt(statsArr[numGuesses]) + 1);
for (int i = 0; i < statsArr.length; i++) {
writer.append(statsArr[i] + ";");
}
writer.close();
}
Some extra context if needed, this is essentially for a Wordle clone sort of thing for a Discord bot I have. numGuesses is the number of guesses it took to get the word correct. The String being written in and being read is 7 numbers divided up by a semicolon, the first number is the current win streak, the second number is number of times you've won in 1 guess, and so on. The testing I've done seems to place the error somewhere before the scanner closes. A first run through will correctly write the numbers, so if the word was guessed in 3 attempts the file will contain "1;0;0;1;0;0;0;", but the next time the method is called it essentially starts from scratch. Checking the temp variable just after the if statement on a second run through just shows "0;0;0;0;0;0;0;". Sorry for the long-windedness, just trying to provide all possibly helpful details. Thank you in advance!
-
Consider the JavaDoc which states "Whether or not a file is available or may be created depends upon the underlying platform.". So what is happening here, is that when you use new FileWriter(*filepath*) the file is being locked/created blank, so when you use new Scanner(new File(*filepath*)); and scan.hasNextLine() you get a null/empty value.
The easy solution is to simply move the FileWriter further down in your code, and only open it after the scanner has been closed. Also add an else to your if statement so you know if there is an issue with reading from the scanner:
//Move the below line to be later in the code
//FileWriter writer = new FileWriter(*filepath*);
Scanner scan = new Scanner(new File(*filepath*));
String temp = "0;0;0;0;0;0;0;";
if (scan.hasNextLine()) {
temp = scan.nextLine();
}
//Add some debugging
else{
System.out.println("ERROR no data could be read");
}
String[] statsArr = temp.split(";");
scan.close();
statsArr[0] = Integer.toString(Integer.parseInt(statsArr[0]) + 1);
statsArr[numGuesses] = Integer.toString(Integer.parseInt(statsArr[numGuesses]) + 1);
//Create the flie writer here instead
FileWriter writer = new FileWriter(*filepath*);
for (int i = 0; i < statsArr.length; i++) {
writer.append(statsArr[i] + ";");
}
writer.close();
Now assuming the file exists and can be edited, and where numGuesses = 3, then for the following contents:
1;2;3;4;5;6;7;
The output of running the code is as expected (+1 to the 0 and 3rd index)
2;2;3;5;5;6;7;
The reason you only saw 0;0;0;0;0;0;0; was because the code was failing to read from the scanner, and always using the temp value from this line String temp = "0;0;0;0;0;0;0;";. By adding the else check above we can see when it fails.
FileWriter writer = new FileWriter(*filepath*); clears the contents of the file you are trying to read from. You need to move this line after scan.close();

Reading multiple integers in multiple lines

I am currently writing my Bachelor's thesis in graph theory and use the java scanner to convert a txt file with edges into my Java class graph. My txt file looks like this:
1 2 72 3
2 3 15 98
4 7 66 49
5 6 39 48
6 9 87 97
8 13 31 5
The ints are ordered as: source vertex, sink vertex, cost, capacity.
My Code looks like:
Graph graph = new Graph(false);
File f = new File("Filepath");
Scanner in = new Scanner(f);
while (in.hasNextLine())
{
for (int i =1; i<= numberEdges; i++)
{
String s = in.nextLine();
try (Scanner inscan = new Scanner(s)) {
while (inscan.hasNext())
{
int source = inscan.nextInt();
int sink = inscan.nextInt();
double cost =inscan.nextDouble();
double capacity = inscan.nextDouble();
Vertex Source = new Vertex(source);
Vertex Sink = new Vertex(sink);
Edge edge = new Edge(Source,Sink, cost, capacity);
graph.addEdge(edge);
}
}
}
}
in.close();
I tried to scan each line in a String and then scan the String into my Variables.
It always throws a "NoLineFound" Exception in the first line of the for loop and if I try it with outputing the lines I get none. But when I disable the second scanner and try again I get all lines in the ouput but at the end still a "NoLineFound" Exception.
I checked my txt File and the last line doesn't have a UTF8 line ending, but I don't know how to give it one.
I think that your problem comes from that :
while (in.hasNextLine()){
for (int i =1; i<= numberEdges; i++)
{
First, iteration is redundant (while or for are unitary enough for reading each line. You have to do choice between them).
Besides if your file has less line than numberEdges, a java.util.NoSuchElementException will be raised.
If the number of line is constant in the file, use a for:
for (int i =1; i<= numberEdges; i++)
remove the enclosing while (in.hasNextLine()). It is not required. Iteration control is already done by the for.
If the number of lines in the file may vary, use only a while :
while (in.hasNextLine()){
But anyway, don't use both.
With Java 8 streams:
Files
.lines(f.toPath())
.map(l ->Arrays.stream(l.split(" ")).mapToDouble(Double::parseDouble).toArray())
.map(a->new Edge(new Vertex((int)a[0]), new Vertex((int)a[1]), a[2], a[3]))
.forEach(graph::addEdge);
You are reading nextLine() in a loop after a single check for hasNextLine(). You need to perform a check after each read in order to avoid the "NoLineFound" exception.
It looks like the nested loop is completely unnecessary. You can read file line-by-line, ignoring empty lines, and build your graph without prior knowledge of the number of edges that it has:
Graph graph = new Graph(false);
File f = new File("Filepath");
Scanner in = new Scanner(f);
while (in.hasNextLine()) {
String s = in.nextLine();
try (Scanner inscan = new Scanner(s)) {
if (!inscan.hasNext()) {
continue; // Ignore empty lines
}
int source = inscan.nextInt();
int sink = inscan.nextInt();
double cost =inscan.nextDouble();
double capacity = inscan.nextDouble();
Vertex Source = new Vertex(source);
Vertex Sink = new Vertex(sink);
Edge edge = new Edge(Source,Sink, cost, capacity);
graph.addEdge(edge);
}
}
in.close();
Just perform a check after reading to avoid the "NoLineFound" exception.
You can use the below code to scan the file:
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Reading multiple data types from a CSV file in Java

So I want to create a constructor that reads in a line of a file from a csv and save the first token into a variable and the remaining tokens into an array. This constructor will be used in a gradebook application but being new to txt/file manipulation I'm having a hard time.
A line will look like:
Billy Bob,68,79,95,83
I want to separate the tokens into these:
name = Billy Bob
grades[] = "68,79,95,83"
here is the code I have so far:
import java.io.*;
public class gradeBook {
public static void main(String[] args){
System.out.println("Java Grade Book version 1.0");
int lineCounter = 0;
String array[];
try{
File data = new File("/file/path/that/works");
InputStream f = new FileInputStream(data);
BufferedReader br = new BufferedReader(new InputStreamReader(f));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line); // just here to check that the code is working thus far
//insert code here
//name should equal first token (which is two names like Billy Bob)
//grades[] should contain the other double type tokens (e.g. 56,87,89,90)
}
br.close();
}
catch(Exception e){
System.err.println("Error: File Couldn't Be Read");
}
}
}
And I want to loop through the file to get as many students as are on the file stored so I can manipulate the grades for averages among other things. This is a personal project to help improve my developing skills so any help, useful tutorial links, and tips will be greatly appreciated. But please don't suggest simplistic examples like the many tutorials I have already read that only use one data type.
Thanks for any help!
Split the line into an array;
String[] input = line.split(",");
String variable = input[0];
int[] grades= new int[input.lenght - 2];
for(int i = 1; i < input.length; i++)
{
grades[i] = input[i];// you might have to do Integer.pareseInt(input[i]);
}
I did not write this in an IDE, but the logic should be correct.
You are going to run into a new problem. You grade book will only contain the last entry. Try using a 2D array for grades and 1D array for names; I personally would not use arrays. I would use arraylist.
So I haven't tested computing my tokens with methods or anything else yet but I have tokenized the line to sum (ha ha oops, meant some) degree with this bit of code:
String[] tokens = line.split(",");
String name = tokens[0];
String grade1 = tokens[1];
String grade2 = tokens[2];
String grade3 = tokens[3];
String grade4 = tokens[4];

Reading txt file, then count unique words and put them into arraylist

I got this assignment for school and all my other methods are working just fine, but reading unique words just doesn't work for me.
My method for reading txtfile:
public void lesBok(String filnavn) throws Exception {
File file = new File(filnavn);
Scanner innlestfil = new Scanner(file);
while (innlestfil.hasNextLine()) {
String s = innlestfil.nextLine();
if((ord.contains(s))){
for(i = 0; i < ord.size(); i++){
if(ord.get(i).toString().equalsIgnoreCase(s)){
ord.get(i).oekAntall();
}
}
}else{
Ord nyttOrd = new Ord(s);
ord.add(nyttOrd);
}
}
}
It reads the txt file, but the problem is that it doesn't difference from unique words.
So if a txt file is for example
hey
My
name
is
hey
It reads 5 words instead of 4.
When the same word pops up, I want it to run this method:
public void oekAntall(){
antall ++;
If you are not specifically required to read it in one word at a time, why not read the entire line and then parse it? I would recommend the StringTokenizer class to accomplish this. I'll write out some pseudo code to show what I mean.
String inputLine = sc.readLine();
StringTokenizer st = new StringTokenizer(inputLine, " "); //parse on spaces
while(st.hasMoreTokens()) {
//Parse tokens
array[x] = st.nextToken();
}

How to read in txt file with multiple Lines of Strings

I'm trying to make an array of strings using a list of names coming from a txt file.
So for example: If I have string[] names = {all the names from the txtfile(one name perline)}
I want to pass "names" into a method that takes in a array like "names"(the one I made above). The method will then run the names through another for loop and create a linked list. I'm really confusing myself on this and tried number of things but nothing seems to work. Right now It'll print out the first name correctly but every name after that just says null. So I have about 70 nulls being printed out.
public static void main(String[] args) {
//String[] names = {"Billy Joe", "Alan Bowe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
Scanner in = new Scanner(System.in);
System.out.println("Enter File Name: ");
String Finame = in.nextLine();
System.out.println("You Entered " + Finame);
try {File file = new File(Finame);
BufferedReader readers = new BufferedReader(new FileReader(file));
// String nameLine = ;
String[] name;
name = new String[73];
String[] nameTO;
String nameLine;
// while ((nameLine = readers.readLine()) != null) {
for (int i = 0; i < name.length; i++){
name[i] = readers.readLine();
x.populateNodes(name);
} //}
} catch(IOException e) {
}
Why is x.populateNodes(name) inside the loop? Wouldn't you be populating it after filling your array?
Since I've no idea what BigNode is, I assume it should be one of the following
x.populateNodes(name[i]) inside the loop or x.populateNodes(name) outside the loop.

Categories

Resources