how do i use a scanner to read a file object - java

like the question how would I use a file object taken from the File class
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/io/File.html
and use a scanner object wrapped around this to read the file,
then say a example like this is contained in the file,
Student{name=Jill Gall,age=21,gpa=2.98}
separate it into fields, skip next step as I just have to call the setters here, and then set the values
I then to save the fields as a Student Object and then save those in a array that I can return?
I'm not really looking for a solution to the entire problem here I'm just wondering as to what the syntax is for calling a scanner object wrapped around a File object to read it, I can use substring to grab the fields to separate and save them onto the new fields, and I'm pretty sure I can just use a for loop to load these onto a array that i can return, the only reason I listed out the entire problem for you guys is so I can give you guys the most details about the task as I can give here
right now my best attempt is this
Scanner n = new Scanner(System.in);
n.commandgoeshere?(filename);
how would I get the scanner to output the data so that i can take a substring and do the stuff i need to do above?

You have to provide an input stream in the constructor of the scanner, atm you are providing the system input stream (from the console) to the scanner. I think something like this is what you are looking for:
File file = new File("");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String nextLine = scanner.nextLine();
// or use regex ?
String extractedPattern = scanner.next("some pattern");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Related

easiest way to read a java file - is there a simpler auternative to JSON

I am writing a small java method that needs to read test data from a file on my win10 laptop.
The test data has not been formed yet but it will be text based.
I need to write a method that reads the data and analyses it character by character.
My questions are:
what is the simplest format to create and read the file....I was looking at JSON, something that does not look particularly complex but is it the best for a very simple application?
My second question (and I am a novice). If the file is in a text file on my laptop.....how do I tell my java code where to find it....how do I ask java to navigate the win10 operating system?
You can also map the text file into java objects (It depends on your text file).
For example, we have a text file that contains person name and family line by line like:
Foo,bar
John,doe
So for parse above text file and map it into a java object we can :
1- Create a Person Object
2- Read and parse the file (line by line)
Create Person Class
public class Person {
private String name;
private String family;
//setters and getters
}
Read The File and Parse line by line
public static void main(String[] args) throws IOException {
//Read file
//Parse line by line
//Map into person object
List<Person> personList = Files
.lines(Paths
.get("D:\\Project\\Code\\src\\main\\resources\\person.txt"))
.map(line -> {
//Get lines of test and split by ","
//It split words of the line and push them into an array of string. Like "John,Doe" -> [John,Doe]
List<String> nameAndFamily = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(line);
//Create a new Person and get above words
Person person = new Person();
person.setName(nameAndFamily.get(0));
person.setFamily(nameAndFamily.get(1));
return person;
}
).collect(Collectors.toList());
//Process the person list
personList.forEach(person -> {
//You can whatever you want to the each person
//Print
System.out.println(person.getName());
System.out.println(person.getFamily());
});
}
Regarding your first question, I can't say much, without knowing anything about the data you like to write/read.
For your second question, you would normally do something like this:
String pathToFile = "C:/Users/SomeUser/Documents/testdata.txt";
InputStream in = new FileInputStream(pathToFile);
As your data gains more complexity you should probably think about using a defined format, if that is possible, something like JSON, YAML or similar for example.
Hope this helps a bit. Good luck with your project.
As for the format the text file needs to take, you should elaborate a bit on the kind of data. So I can't say much there.
But to navigate the file system, you just need to write the path a bit different:
The drive letter is a single character at the beginning of the path i.e. no colon ":"
replace the backslash with a slash
then you should be set.
So for example...
C:\users\johndoe\documents\projectfiles\mydatafile.txt
becomes
c/users/johndoe/documents/projectfiles/mydatafile.txt
With this path, you can use all the IO classes for file manipulation.

How to create JSON file from java without duplicating element?

I'm trying to make a simple dictionary program based on server-client socket communication. I'm trying to save user word and meaning input as a JSON file (which is dictionary data to search later on) but when I do add query it ends up with having duplicated JSON objects
for example, if I add happy and then weather and hello, the result written in JSON file is
like below
{"hello":"greeting"}{"happy":"joy","hello":"greeting"}
{"happy":"joy","weather":"cold","hello":"greeting"}`
instead of getting
{"hello":"greeting"}{"happy":"joy"}{"weather":"cold"} like I wanted
how can I fix this problem?
my code for that function is
case "add":{
FileWriter dictionaryWriter = new FileWriter("dictionary.json",true);
//split command again into 2 part now using delimiter ","
String break2[] = msgBreak[1].split(",");
String word = break2[0];
String meaning = break2[1];
dictionary.put(word, meaning);
System.out.println("Writing... " + word+":"+meaning);
dictionaryWriter.write(dictionary.toString());
//flush remain byte
dictionaryWriter.flush();
//close writer
dictionaryWriter.close();
break;}
this function is in while(true) loop with other dictionary functions
I tried to remove the appending file part, but when I remove the (,true) part the duplication error stopped but whenever I get a new connection, new dictionary file is created instead of having all data saved.
If anyone can help me solve this problem, I would appreciate it a lot!
Thanks you in advance.
You can try to create a new dictionary every time instead of using the existing one
Map<String, String> dictionary = new HashMap<>();
dictionary.put(word, meaning);
...

Using File I/O in Java

I am trying to create a pet project for the summer, which requires a large amount of information. I think the best way to do this would be to store all the data in a text file, and proceed to pull the necessary information from that file when it's called upon. My question, though, is how to pull specific sets of information, and then proceed to store parts of that into an array perhaps or some other data structure which would allow for that to be more easily accessed during the execution of the program. The text file would have hundreds (if not thousands) of "sets" of data, and each "set" will have multiple parts. For example,
ID001 Name Data1 Data2 Data3 TypeData
Where ID001 would just be an index, the name would be a string, the three "Data" would be integers, and the TypeData would be a String (for example). What is the best way to go about taking all that information (there'll actually be more data per "set" but for simplicity's sake let's go with just this) and separating it so each part is usable by a different part of the program? Is this even the right way to go about doing something like this? I was originally imagining something along the lines of a spreadsheet but I don't know how to use something quite like that as I/O for a program.
Here's one possible way of reading a file and getting just the "chunks":
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
You can take a look at the Java Scanner Tutorial for other ideas.

Saving variable state in between sessions?

So I'm in the process of developing a Java IRC bot as a bit of a side project for a friend of mine, and while development is going well, I'm a little unsure as how to save the current state of certain variables in between sessions. It doesn't have a GUI, so I didn't think that it would be too complex, but my searching efforts have been futile thus far.
Thanks.
It will depend on the sort of variables you want to keep, but all methods will require you to write some sort data to a file.
If you only need to keep a handful of variables, you could consider implementing a .config file that could be a simple delimited text file.
If it's an entire object that you want to keep track of, say, a player in an irc game, one option you have is to parse the object into JSON, and save it to a textfile, for reading later. You can use Gson for this
example for a 'player' object:
public String savePlayer(String playerName){
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String playerFile = System.getProperty("user.dir")+"\\players\\"+playerName;
String jsonplayers = gsonPretty.toJson(players.get(playerName));
try{
FileWriter writer = new FileWriter(playerFile+".json");
writer.write(jsonplayers);
writer.close();
return "Player file saved successfully!";
}catch(Exception e){
e.printStackTrace();
}
return "Something went wrong";
}
you can then create a load method that either has the file name hard coded, or a string input to determine which file to load, and use something like:
playerFromJson = gson.fromJson(jsonString, Player.class);
to use that object in the code

Java, Turn Each Row of a CSV into a string

Hello I'm a newbie in Java using BlueJ. I have a csv file that contains a load of data in a table arrangement. I'm trying to find a way to take this information and find out how many comma separated values there are in the first row then regardless of rows put each comma separated value into an array.
Does anyone have any advice on how to do this?
Thanks in advance, Harry.
CSV parsing can be tricky because of the need to support quoted values. I suggest not writing your own CSV parser, but using an existing library such as http://opencsv.sourceforge.net/.
You can use the Scanner file, to read each line of the file, something similar to:
// create a File object by giving the filepath
File file = new File("C:\\data.csv");
try {
// Create a new scanner class that will read the file
Scanner scanner = new Scanner(file);
// while the file has lines to read
while (scanner.hasNextLine()) {
// read the line to a string
String line = scanner.nextLine();
// do what you need with that line
}
// catch the exception if no file can be found
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Here is another library to handle csv file. javacsv
Code example is here

Categories

Resources