Is there a problem with BufferedWriter in JAVA? - java

I'm quite new in OOP and Java programming, so please, forgive me.
I wrote a small class in which I try to write a String in a file using the BufferedReader class.
Everything works just fine, but the file is "empty", I mean that I can't see anything inside.
But for sure, data are stored, because when I close Eclipse and re open it again and run the driver class to make my tests, data are restored from the file.
By the way I use a "try with resources" mechanism so my file is "closed" automatically.
Does someone already meet this problem?
My Eclipse version is "2018-12"
Below, you have the small class with a "writeToFile" method in which I use the BufferedReader class.
package parlons.code.tipcalulator.utilities;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileManagement {
private File tipFile;
public FileManagement(String tipsFileName) {
this.tipFile = new File("/"+tipsFileName);
}
public String readFromFile() {
String tip = null;
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(this.tipFile))) {
tip = bufferedReader.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tip;
}
public void writeToFile(String decimal) {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tipFile,true))){
bufferedWriter.write(decimal);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below, you'll find the Driver class for testing purposes.
package parlons.code.tipcalulator.utilities;
public class UtilitiesTestDriver {
public static void main(String[] args) {
String decimal = "108";
FileManagement fileManagement = new FileManagement("tipFile.txt");
fileManagement.writeToFile(decimal);
System.out.println(fileManagement.readFromFile());
}
}

As per Makoto's comment above, everything works fine if you change to e.g.:
this.tipFile = new File("./"+tipsFileName);
This would create the tipFile.txt file (containing 108) in the root directory of your project (as opposed to the root of the filesystem - where you would probably not have write permission.)

Related

I can't write on multiple lines in a txt file in java

So I'm trying to write in a text file, nothing too complicated, but for some reason the new text that i want to add doesn't change lines, it keeps going on the same line, and I can't figure out why. The irrelevant parts are being commented so don't worry about them.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
public static void main( String args[]) {
int a = 32;
int b=12;
int c=33;
List<Integer> myList = new ArrayList();
myList.add(a);
myList.add(b);
myList.add(c);
/* for(int s:myList)
{
System.out.println(s);
}
*/
//Om ar= new Om("Alex",21,185);
//System.out.println(ar);
try{
File myObj = new File("filename.txt");
if(myObj.createNewFile()){
System.out.println("File created " + myObj.getName());
}
else
{
System.out.println("File already exists");
}
}
catch (IOException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
try {
FileWriter myWriter = new FileWriter("filename.txt");
for(int i=1;i<10;i++)
{
myWriter.append("This is a new file, nothing sus here."+i + " ");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Wrap your FileWriter in a BufferedWriter to make writing to the file more efficient.
Then you can use the newLine() method of the BufferedWriter to add a newline String to the file as you require. The newLine() method will write out the appropriate string for your current platform.

The package java.util.logging is not accessible in Java

I am trying run simple hello word java program and want to log hellow world.
But I am getting error as
"The package java.util.logging is not accessible" on the statement
import java.util.logging.*; in eclipse.
I am using Java 11 version
Complete code below
package myproject;
import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.*;
public class FileOperations {
public static void main(String[] args) {
// Create a Logger
Logger logger = Logger.getLogger(FileOperations.class.getName());
// Call info method
logger.info("This is message 1");
// TODO Auto-generated method stub
File file=new File("myFile.txt");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(2);
System.out.println("File operation completed");
Logger.log(Level.INFO, "My first Log Message");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you have a module-info.java file, then add
requires java.logging;
Maybe the problem with creating a Logger object?
Logger logger = Logger.Leve
It seems that it is not completed.

FileOutputStream doesn't show FileNotFoundException

for FileOutputStream, it will throw a FileNotFoundException if the file doesn't exist, but it will create it if it can.
I dont have a Sample.txt in my project root
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is:
I cannot see the Output of the "File Not Found" from the Terminal. How did it happen?
Thank you
You can set Sample.txt as a File first and check if it exists with .canWrite()
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}

Java - How can I get the file paths of the contents of a given directory and write them to a text file?

I've found answers to various questions on here before, but this is my first time asking one. I'm kicking around an idea for my final project in my computer programming class, and I'm working on a few proof of concept programs in Java, working in Eclipse. I don't need anything more than to get the filepaths of the contents of a directory and write them to a .txt file. Thanks in advance!
Edit: I am posting my code below. I found a snippet of code to use for getting the contents and print them to the screen, but the print command is a placeholder that I'll replace with a write to folder command when I can.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ScanFolder {
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
}
EDIT: I've enclosed the OutputStreamWriter in a BufferedWriter
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("txt.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
writeContentsOfFileToAFile(new File("."), out, true); // change true to
// false if you
// don't want to
// recursively
// list the
// files
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void writeContentsOfFileToAFile(File parent, BufferedWriter out, boolean enterIntoDirectory) {
for (File file : parent.listFiles()) {
try {
out.write(file.toString() + "\r\n");
} catch (IOException e) {
e.printStackTrace();
}
if (enterIntoDirectory && file.isDirectory())
writeContentsOfFileToAFile(file, out, enterIntoDirectory);
}
}
Is this what you need?

java eclipse fails to detect a "bin" located file

I use eclipse and put a File called "example.txt" into the bin-folder where the class files are generated (and into the sub-folder of the package). But still, the program allways prints out the error message i wrote for the case the file is not found.
Main Class:
import java.io.BufferedReader;
public class Main {
public static void main(String[] args){
BufferedReader file = Console.file("example.txt");
...
}
Console Class:
public final class Console {
public static BufferedReader file(String args) {
BufferedReader file = null;
try {
file = new BufferedReader(new FileReader(args));
} catch (FileNotFoundException e) {
println("Error, file not found!");
System.exit(1);
}
return file;
}
}
any ideas?
For the Eclipse project, the current path is the project folder, not the BIN directory, you can use the code below to get the current path so that you will know where to put and how to access the file.
import java.io.File;
import java.io.IOException;
public class MainTest {
public static void main(String[] args)
{
File directory = new File("");
try {
System.out.println(directory.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So in your case, the path you specify should be: ./bin/example.txt

Categories

Resources