filewriter not writing to file even though no error - java

I have some code that I have been using for a long time to write to a .txt file in the csv format, but for some reason it will no longer actually produce a new file. The file writing function is executing normally and flushing and closing without any error, but then no file is created. Below is a simplified example that is still not working.
`
import java.io.FileWriter;
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String filename = "SO example";
FileWriter writer=null;
try{
writer = new FileWriter(filename);
}
catch(Exception e){
System.out.println("exception: " + e.getMessage());
}
try{
writer.append("some text\n");
System.out.println("after append");
} catch (Exception e){
System.out.println("exception: " + e.getMessage());
}
try{
writer.flush();
writer.close();
System.out.println("finished writing file "+ filename);
}catch (Exception e){
System.out.println("exception 3: "+e.getMessage());
}
}
}
`
This should create a file called "SO example, but when I search for that file on my computer, it doesn't show up. I am using Netbeans btw. Does anyone know what might be the problem?
Thanks,
Paul

I just ran your code on my computer and everything seems to work fine. I am running Ubuntu and eclipse, however.
I would recommend checking where NetBeans stores your project directory and check in there. Don't forget to refresh the directory if you are looking for the file from the directory hierarchy manager within NetBeans.

Related

Java how to test file utility that are void methods?

How exactly would I test classes or methods that involve writing out files, or moving files around from directory to directory? Let's say I have this helper method as one of Spring MVC's Service layer methods:
private void writeFileOut(String fileContents, String fileName) throws IOException {
File fullFilePath;
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try {
fullFilePath = new File("/temp/directory/" + fileName);
fileWriter = new FileWriter(fullFilePath);
bufferedWriter = new BufferedWriter(fileWriter);
if (bufferedWriter != null) {
bufferedWriter.append(fileContents);
}
} catch (IOException e) {
LOGGER.info("Error writing file out: " + e.getMessage());
throw e;
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
throw e;
}
}
}
How exactly is this method testable? It isn't producing anything and I can't think of a way to test this is working exactly.
First things first: why reinvent the wheel instead of using Files.writeString?
Assuming you are looking for a more general solution to test code that touches the file system: I'd try to keep any external resource (network, database, other processes, file system) out of my unit tests. You'll end up with brittle tests that depend on e.g., file system details (latency, cleanup between tests, tests running in parallel may step on each others toes).
Then: please use try with resources:
private void writeFileOut(String fileContents, String fileName) throws IOException {
File fullFilePath = new File("/temp/directory/" + fileName);
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fullFilePath))) {
bufferedWriter.append(fileContents);
}
catch (IOException e) {
LOGGER.info("Error writing file out: " + e.getMessage());
throw e;
}
}
Now your code does 3 things:
create the path for the file
write the given data to the file
log if an error occurs
It's often easiest to move code you want to test into new methods that you can call separately, instead of having to test through all the other code. So isolate pieces of code, especially the code that tries to use the file system.
private void writeFileOut(String fileContents, String fileName) throws IOException {
File fullFilePath = new File(makeTempPath(fileName));
try (Writer bufferedWriter = makeWriter(fullFilePath)) {
bufferedWriter.append(fileContents);
}
catch (IOException e) {
LOGGER.info("Error writing file out: " + e.getMessage());
throw e;
}
}
String makeTempPath(String fileName) {
return "/temp/directory/" + fileName;
}
Writer makeWriter(String fullFilePath) {
return new BufferedWriter(new FileWriter(fullFilePath));
}
Now you can test makeTempPath separately.
You can mock makeWriter when you test writeFileOut. You can check that it receives what it was supposed to receive. You can have it throw to trigger the error handling.
When you mock, you can use a framework like Mockito or you create a derived class for the methods you want to mock and override them. Note that makeWriter returns a Writer. In real life this is the BufferedWriter that writes to a file. In testing you can return a StringWriter to capture what gets written.
Either way, be careful not to mock too much, or you may end up just testing your mocks, not the production code.
to test writing out files: Better to use file Comparison i.e have reference file(expected file) and compare it with the generated one.
for your reference: Comparing text files with Junit
moving files around from directory to directory: after moving file u can check for existance of file eg. file.exists() in the destination directory and also of course u can verify the contents also.
Eg: File file = new File("file Path in destination folder");
assertTrue("File doesnot exit",file.exists());

How can I open a file in java without its contents been removed?

I want my program to create a file for the user (just for the first time) and write some information to it (it's not just a line and also can be adjusted anytime later). So I did this:
public void write() {
try {
file = new File("c:\\Users\\Me\\Desktop\\text.txt");
if(!file.exists()) // I found this somewhere on the internet for File class
file.createNewFile(); // not to remove contents. I have no idea if it works
writer = new Formatter(file);
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close();
}
It works but there some problems:
When the file gets opened later, as default, the File class removes its contents.
When the information is written to the file and Formatter got closed, next time somewhere else in the program when I use it again to write to the file, the information gets updated and not added to the previous ones. And if I don't close it, it won't write.
first af all, this code here:
if(!file.exists())
file.createNewFile();
it only creates a new file in case it doesn't exists in your path.
To write on your file without overwriting it I recommend you to do this:
FileWriter fileWriter;
public void write() {
try {
file = new File("c:\\Users\\Me\\Desktop\\text.txt");
if(!file.exists())
file.createNewFile();
// use a FileWriter to take the file to write on
fileWriter = new FileWriter(file, true); // true means that you do not overwrite the file
writer = new Formatter(fileWriter); // than you put your FileWriter in the Formatter
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close();
}
Hope this was helpfull! :)
As people mentioned above, I had to pass the file through the constructor of FileWriter class. this way my first problem got solved (I mentioned them in the question) and for the second one, I had to reopen the Formatter whenever I wanted to add more.
public void write() {
try {
writer = new Formatter(new FileWriter(file,true);
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close(); }
creation and initialization of file should be done once and outside the method.

Not writing to text file

I currently am having problems writing to the text file in my code, the entirety of the program is hit and everything will print out to the console. no errors. But the file is empty. Any suggestions?
public textFiles(String filePath)
{
File file = new File(filePath);
try{
fstream = new FileWriter(filePath,true);
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
out = new BufferedWriter(fstream);
System.out.println("try");
addToText("WOOOOHOOO");
System.out.println(file.exists());
}
public void addToText(String Line)
{
try {
out.write(Line);
out.newLine();
} catch (IOException e) {
System.err.println("writing Error");
}
System.out.println("SHOULDA F****** WORKED");
}
You're never closing the stream, and so probably never flushing the stream either - the text essentially gets cached when you print it out, and gets flushed to the file in chunks (usually chunks that are much bigger than what you're writing, hence the lack of output.)
Make sure you close the stream when you're done (fstream.close();), and it should work fine (the stream will automatically flush to clear any output when it's closed).
Try this code to write a .txt file in any drive.
try
{
String ss="html file write in java";
File file= new File("F:\\inputfile\\aa.txt");
FileWriter fwhn= new FileWriter(file);
fwhn.write(ss);
fwhn.flush();
}
catch(Exception ex)
{
}

Writing Multiple Lines To A File At Different Times

I have the basics of my program finished.
The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.
My goal is to get all of this output into a text file.
Currently I create a scanner for reading:
static Scanner input = new Scanner(System.in);
Then in my main driver method I create a Formatter:
public static void main(String[] args) {
Formatter output = null;
try{
output = new Formatter("output.txt");
}
catch(SecurityException e1){
System.err.println("You don't have" +
" write accress to this file");
System.exit(1);
}
catch(FileNotFoundException e){
System.err.println("Error opening or" +
" creating file.");
System.exit(1);
}
After each time I expect output I have placed this bit of code:
output.format("%s", input.nextLine());
And finally I close the file with
output.close()
The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:
output.format("%d", i);
where i is an integer of 0 and the file writes correctly.
However, I cannot seem to get it to work for an entire line, or for the output at all.
Please help!
I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.
import java.io.FileWriter;
import java.io.IOException;
try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}

Writing to file from within a servlet(Deployer:Tomcat)

I am using the following code to write to a file from a servlet in Tomcat container. I don't worry if the file gets overwritten during each deploy.
BufferedWriter xml_out = null;
try {
xml_out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getServletContext().getRealPath("/")
+ File.separator + "WEB-INF" + File.separator
+ "XML.xml"), "UTF8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
xml_out.write(xml);
xml_out.flush();
xml_out.close();
} catch (IOException e) {
e.printStackTrace();
}
However, the file writing is not successful (it doesn't get written in the hard disk). Also, there isn't any exception that gets caught! Is there some security thing in Tomcat that is preventing the file from being written ?
Your code has both "/" and the windows file separator at the start of the filename passed to getRealPath(), Java interprets slashes in filenames according to the current OS.
Not using the file separators might give a better result:
String filename = getServletContext().getRealPath("/WEB-INF/XML.xml");
log.debug("Using XML file: " + filename);
xml_out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename),"UTF8"));
Using a separate variable for the filename lets you log it so you can see unexpected results early in de development process.
I has the same issue.
this link helped me to understand where the file was in the hard disk.
Specifically for me, it put the file in the location that is returned by this line:
System.getProperty("user.dir");
In my case the location was: C:\Users\Myself\programming\eclipse for java

Categories