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.
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.
Here I am using FileInputStream class to read data from input.txt. read method is called twice. How does the inputStream object know that it has to read the second character when the read method is called the second time? I mean does inputStream object maintain the offset?
package streams;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
read();
}
private static void read() throws IOException {
InputStream inputStream = new FileInputStream("src/main/resources/input.txt");
int data;
data = inputStream.read();
System.out.println(data);
data = inputStream.read();
System.out.println(data);
inputStream.close();
}
}
Yes the the FileInputStream keeps a reference to a some OS-file handle on which is operates the read method. This file-handle will maintain the offset in the file and will forward it by howerver many bytes were read.
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 have this code where I recursively list all the files from a folder. My question is how to print the output from the console to a .txt file? It would help me a lot if someone could add what is needed in my code.
import java.io.*;
public class Exp {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\User\\Downloads");
rec(f);
}
public static void rec(File file) throws FileNotFoundException {
File[] list = file.listFiles();
for (File f : list) {
if (f.isFile()) {
System.out.println(f.getName());
}
else if (f.isDirectory()) {
rec(f);
}
}
}
}
You are currently outputting to System.out, which is a PrintStream. Instead of doing that, create a PrintStream for a .txt file and pass the PrintStream as an argument to your rec method. Use the try-with-resources idiom to ensure the PrintStream gets closed when you're done with it.
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);