So i have tried every thing but the files keeps over writing the first line, i am passing these methods to another class so the three arguments in method add_records are passed through a scanner.
here is the creating/opening method :
public class Io_Files{
private Formatter output;
public void open_file_normal(String filename) throws IOException
{
{
try
{
FileWriter fileWriter = new FileWriter(filename, true);
output = new Formatter(filename);
}
catch(FileNotFoundException fileNotFoundException)
{
System.err.println("Error");
}
}
}
and here is the code for adding record method:
public void add_records(String a, String b, int c) throws FileNotFoundException{
output.format ("[%s, %s, %d]%n", a, b, c);
}
please if you are able to help provide some comments on why and where to put the code so i can learn too.
cheers
Try using
output = new Formatter(fileWriter);
instead of
output = new Formatter(filename);
Related
I have class Artical:
first variable is code of artical, second variable is name of article and third is price of article.
public class Artical {
private final String codeOfArtical;
private final String nameOfArtical;
private double priceOfArtical;
public Artical(String codeOfArtical, String nameOfArtical, double priceOfArtical) {
this.codeOfArtical= codeOfArtical;
this.nameOfArtical= nameOfArtical;
this.priceOfArtical= priceOfArtical;
}
public void setPriceOfArtical(double priceOfArtical) {
this.priceOfArtical= priceOfArtical;
}
public String getCodeOfArtical() {
return codeOfArtical;
}
public String getNameOfArtical() {
return nameOfArtical;
}
public double getPriceOfArtical() {
return priceOfArtical;
}
}
I want in main class to write something like:
Artical a1 = new Artical("841740102156", "LG Monitor", 600.00);
new ShowArticalClass(a1).do();
new WriteArticalInFileClass(new File("baza.csv"), a1).do();
so that data in file will be written in format like this:
841740102156; Monitor LG; 600.00;
914918414989; Intel CPU; 250.00;
Those 2 classes ShowArticalClass and WriteArticalInFileClass arent important, those are abstract classes.*
So my question is: How do I set format to look like this, where every line is new Artical.
A very naive implementation can be the following:
Create a class that in turn creates a CSVWriter (assuming you want to write to a CSV). That class will expose a public method allowing you to pass in a path where the desired csv file lives as well as the Artical object you want to write to this file. Using that class you will format your data and write them to the file. An example of this could be:
public class CsvWriter {
private static final Object LOCK = new Object();
private static CsvWriter writer;
private CsvWriter() {}
public static CsvWriter getInstance() {
synchronized (LOCK) {
if (null == writer) {
writer = new CsvWriter();
}
return writer;
}
}
public void writeCsv(String filePath, Artical content) throws IOException {
try (var writer = createWriter(filePath)) {
writer.append(getDataline(content)).append("\n");
}
}
private String getDataline(Artical content) {
return String.join(",", content.getCode(), content.getName(), Double.toString(content.getPrice()));
}
private PrintWriter createWriter(String stringPath) throws IOException {
var path = Paths.get(stringPath);
try {
if (Files.exists(path)) {
System.out.printf("File under path %s exists. Will append to it%n", stringPath);
return new PrintWriter(new FileWriter(path.toFile(), true));
}
return new PrintWriter(path.toFile());
} catch (Exception e) {
System.out.println("An error has occurred while writing to a file");
throw e;
}
}
}
Note that this will take into account where the file provided is already in place (thus appending to it). In any other case the file will be created and written to directly.
Call this write method in a fashion similar to this:
public static void main(String... args) throws IOException {
var artical = new Artical("1", "Test", 10.10);
CsvWriter.getInstance().writeCsv("/tmp/test1.csv", artical);
var artical2 = new Artical("2", "Test", 11.14);
CsvWriter.getInstance().writeCsv("/tmp/test1.csv", artical2);
}
With that as a starting point you can go ahead and modify the code to be able to handle list of Artical objects.
If you really need to support CSV files though I would strongly recommend into looking at the various CSV related libraries that are out there instead of implementing your own code.
How do I write in same text file from different classes in java.
One of the class call method from another class.
I do not want to open BufferedWriter in each class, so thinking if there is a cleaner way to do this ?
So essentially, I want to avoid writing the following code in each class
Path path = Paths.get("c:/output.txt");
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write("Hello World !!");
}
A good way of doing this is to create a central writing class, that maps from a file name to a reader/writer-object. For example:
public class FileHandler {
private static final Map<String, FileHandler> m_handlers = new HashMap<>();
private final String m_path;
private final BufferedWriter m_writer;
// private final BufferedReader m_reader; this one is optional, and I did not instantiate in this example.
public FileHandler (String path) {
m_path = path;
try {
m_writer = Files.newBufferedWriter(path);
} catch (Exception e) {
m_writer = null;
// some exception handling here...
}
}
public void write(String toWrite) {
if (m_writer != null) {
try {
m_writer.write(toWrite);
} catch (IOException e) {
// some more exception handling...
}
}
}
public static synchronized void write(String path, String toWrite) {
FileHandler handler = m_handlers.get(path);
if (handler == null) {
handler = new FileHandler(path);
m_handlers.put(path, toWrite);
}
handler.write(toWrite);
}
}
Be aware that this behavior does not close the file writers at any point, because you don't know who else is currently (or later on) writing. This is not a complete solution, just a strong hint in a good direction.
This is cool, because now you can "always" call FileHandler.write("c:output.txt", "Hello something!?$");. The FileHandler class could be extended (as hinted) to read files too, and to do other stuff for you, that you might need later (like buffer the content, so you don't have to read a file every time you access it).
I am trying to get user input, however I am getting
illegal start of expression at:
public static String askTheUser() throws IOException
Complete code:
Edit: I have made most of the changes you guys suggested so now I have this:
import java.io.BufferedReader;
public class Driver
{
public static void main(String[]args)
{
Dice dice;
Craps craps;
userResponse = askTheUser();
while(userResponse.equalsIgnoreCase("yes"))
{
craps = new Craps();
while(!craps.gameOver())
{
craps.roll();
//print out results of roll
}
//print out game results: if(craps.gameWon()...
userResponse.askTheUser();
}
}
public static String askTheUser() throws IOException
{
BufferedReader dataIn = new BufferedReader( new InputStreamReader(System.in) );
String data;
System.out.print("Want to play craps? Yes or No");
data = dataIn.readLine();
if(data.equals("y") || data.equals("yes"))
{
return "yes";
}
else
{
return "no";
}
}
}
However I am still getting cannot find symbol at public static String askTheUser() throws IOException. So might I be missing an import that I don't know of?
you declared askTheUser method inside main method. rip it out off the main method.
public static void main(String[]args)
{
//code that goes inside main
}
public static String askTheUser() throws IOException
{
// code that goes in askTheUser
}
and i don't think that keyboard.readline() works?
use:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
in.readLine(); // Convert to string or int needed!
You can't write method inside method in Java.
But you can have many methods in the same class.
Why? Because of Java specifications.. you are simply not allowed to do so.
Note that you can have an anonymous inner class with methods under another method.
I have trouble with write txt file from class FileWrite in my java project , if the PRINT() method were in VehicleCollection class , and called in main class - don't have problems. But I want print method be in different class which named FileWrite and called in main method from this class . Here peace of Code . I hope that i write correct question. if i should Explain more about my code I will .
I have 3 Classes 1st class is :
public class VehicleCollection {
private ArrayList<VehicleInterface> arrList = new ArrayList<>();
public ArrayList<VehicleInterface> getArrList() {
return arrList;
}
void setArrList(ArrayList<VehicleInterface> w){
arrList = w;
}
public void getCollection() throws FileNotFoundException, IOException {
Here Add in ArrayLIst...
}
}
Second class is :
public class FileWrite extends VehicleCollection {
FileWrite(ArrayList<VehicleInterface> w){
setArrList(w);
}
public void print() throws FileNotFoundException {
Writer writer = null;
try {
String text = getArrList().toString();
File file = new File("krasiWrite.txt");
writer = new BufferedWriter(new java.io.FileWriter(file));
writer.write(text);
...
}
Third class is main class :
FileWrite fw = new FileWrite();
fw.print();
here Have error:cannot be applied to given types required ArrayList
File writes are usually buffered by the operating system. You must either close() or flush() the writer to make sure that the changes go to disk. If you're done with the file, just close it. A close will automatically flush the buffers.
Since you are already using Java 7, why not use the try-with-resources construct to avoid having to do things like close streams:
try( File file = new File("krasiWrite.txt");
Writer writer = new BufferedWriter(new java.io.FileWriter(file)); )
{
String text = getArrList().toString();
writer.write(text);
writer.flush(); // this lines takes whatever is stored in the BufferedWriter's internal buffer
// and writes it to the stream
}
catch(IOException ioe) {
// ... handle exception
}
// now all resources are closed.
how do I get the read txt file into the main class?
//main class
public class mainClass {
public static void main(String[]args) {
load method = new load("Monster");
}
}
//scanner class
public class load {
public static void loader(String... aArgs) throws FileNotFoundException {
load parser = new load("resources/monsters/human/humanSerf.txt");
parser.processLineByLine();
log("Done.");
}
public load(String aFileName){
fFile = new File(aFileName);
}
public final void processLineByLine() throws FileNotFoundException {
//Note that FileReader is used, not File, since File is not Closeable
Scanner scanner = new Scanner(new FileReader(fFile));
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
scanner.close();
}
}
public void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Stat is : " + quote(name.trim()) + ", and the value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
}
public final File fFile;
public static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
public String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
Which method do I call from the main class and what variables do I return from that method if I want the text from the file. If anyone has a website that can help me learn scanner(got this source code of the internet and only sort of understand it from JavaPractises and the sun tutorials) that would be great. thanks
First, you probably want to follow standard Java naming conventions - use public class MainClass instead of mainClass.
Second, for your methods, the public has a specific purpose. See here and here. You generally want to label methods as public only as necessary (in jargon, this is known as encapsulation).
For your question - in the Load class, you can append all the text from the file to a String, and add a public getter method in Load which will return that when called.
Add this at the start of Load:
public class Load {
private String fileText;
// ... rest of class
And add this getter method to the Load class. Yes, you could simply mark fileText as public, but that defeats the purpose of Object-Oriented Programming.
public getFileText(String aFileName){
return fileText;
}
Finally, use this new method for log. Note that there is no need to use Object.
private static void log(String line) {
System.out.println(line);
fileText += aObject;
}
You can now get the read file into the main class by calling method.getFileText()
Code was TL;DR
If you want to get all of the data from the load class's .txt file, then you need to write a method in load to get the lines. Something like this would work:
public String[] getFileAsArray() {
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(fFile);
while(in.hasNextLine())
lines.add(in.nextLine();
String[] retArr = new String[lines.size()];
return lines.toArray(retArr);
}