Java File Output Check - java

I have just written a long amount of code and I am trying to write an output file with this code-
File outfile = new File ("output.txt");
PrintWriter outFile = new PrintWriter(outfile);
outFile.printf("%-20s%5s%5s%5s%5s", f,median,avg,min,max);
outFile.println("");
outFile.printf("%-20s%5s%5s%5s%5s", f,median,avg,min,max);
outFile.println("");
outFile.printf("%-27s%5d%5d%5d%5d", firstplayer,P1median,P1avg,PScore.get(0),PScore.get(PScore.size()-1));
outFile.println("");
outFile.printf("%-27s%5d%5d%5d%5d", secondplayer,P2median,P2avg,Player2.get(0),Player2.get(Player2.size()-1));
outFile.println("");
outFile.printf("%-27s%5d%5d%5d%5d",fourthplayer,P4median,P4avg,Player4.get(0),Player4.get(Player4.size()-1));
outFile.close();
Now as I had no errors or exceptions thrown I believe I have succeed in writing an output file, however I have no idea where it is located and how I can check the content of it. I apologize if this is a bad question but I was struggling to find an answer elsewhere, so any help locating the output file or correcting my mistakes would be appreciated greatly.

This will print out the full file path if you're still unsure where it's located:
System.out.println(outfile.getAbsolutePath());
If you want to print out the contents of the file so you can examine it in your program:
//ensure content in file is updated
outfile.flush();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(outfile));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
Make sure to close the file as well.

You should close your file to ensure everything is good.
outFile.close();
You can also flush from time to time if you want those results to appear on disk as you go.
outFile.flush();
Also, you shouldn't name two variables the same except for case. Call your File, file, and your PrintWriter, writer.

I've read from the book of "Core Java", and here is another way to find your file directory,
String dir=System.getProperty("user.dir");
System.out.println(dir);
and through the directory of the console,you may find your file "output.txt"

Related

Java BufferedWriter - newLine() method

I have been encountering a problem for a while now, and have tested every possibility I can think of. Unfortunately, these possibilities did not work.
Basically, I am trying to write to a .txt file using BufferedWriter in Java. I need this setup so that I can have a line in between each piece of data. Imagine this is the text file produced from Java, it should look like this:
line1
line2
Here is my code:
public static void main(String[] args) {
Path path = Paths.get("test.txt");
if (!Files.exists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
System.out.println("Error in creating test.txt! Read the stacktrace
below.");
e.printStackTrace();
}
}
Charset charset = Charset.forName("UTF-8");
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line1";
writer.write(string, 0, string.length());
writer.newLine();
writer.newLine();
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line2";
writer.write(string, 0, string.length());
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
}
The output of this produces a text file as so:
line2
Now, I know I could just combine my two try/catches, and it would work. But this is just a test representation; in my real code, I need to do this separately so I can write in .txt files whenever specific events are triggered.
Basically, the newLine() methods are not saving unless I write text directly after them.
Any help is appreciated, as always!
The second BufferedWriter, or rather the second implicit FileWriter, overwrites the file created by the first one.
Combine the statements as you suggest, or use append mode (inefficient in this case).

Creating a File using PrintWriter in Java, and Writing to that File

I'm trying to write a program that reads a file (which is a Java source file), makes an Arraylist of certain specified values from that file. and outputs that Arraylist into another resulting file.
I'm using PrintWriter to make the new resulting file. This is a summarised version of my program:
ArrayList<String> exampleArrayList = new ArrayList<String>();
File actualInputFile = new File("C:/Desktop/example.java");
PrintWriter resultingSpreadsheet= new PrintWriter("C:/Desktop/SpreadsheetValues.txt", "UTF-8");
FileReader fr = new FileReader(actualInputFile);
BufferedReader br = new BufferedReader(fr);
String line=null;
while ((line = br.readLine()) != null) {
// code that makes ArrayList
}
for (int i = 0; i < exampleArrayList.size(); i++) {
resultingSpreadsheet.println(exampleArrayList.get(i));
}
resultingSpreadsheet.close();
The problem is that when i run this, nothing gets printed to the resultingSpreadsheet. It's completely empty.
BUT, this program works perfectly (meaning that it prints out everything correctly to the resultingSpreadsheet file) when I replace:
File actualInputFile = new File("C:/Desktop/example.java");
which is the file that I want as my input file, and which has a size of 481 KB,
with:
File smallerInputFile = new File("C:/Desktop/smallerExample.txt");
which is really just a smaller .txt example version of the .java source file, and it has a size of 1.08 KB.
I've tried a few things including flushing the PrintWriter, wrapping it around FileWriter, copy-pasting all the code from the .java file into a text file in case it was an extension problem, but these don't seem to work.
I'm starting to think it must be because of the size of the file that the PrintWriter makes, but it's very possible that that's not the problem. Perhaps I need to put everything in a stream (like it says here: http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html)? If so, how would I do that?
Why is reading the bigger actualInputFile and outputting its data correctly such a problem, when everything works fine for the smallerInputFile?
Can anyone help with this?
Check for exceptions while writing to the the excel sheet , because i really don't think its a problem of size. Below is the sample code that is executing successfully and the file size was approx 1 MB.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\AdminController.java"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This should go as a comment, but I do not have the rep. In the documentation it has both write methods and print methods. Have you tried using write() instead?
I doubt it's the size of the file, it may be between the two files you are testing one is .txt, and the other is .java
EDIT: Probably second suggestion of the two. First is just something I noticed with the docs.
The methods of PrintWriter do not throw Exception. Call the checkError() method which would flush the stream as well as return true if an error occurred. It is quite possible that an error occurred processing the larger file, an encoding error for instance.
Check your program. When the file is empty it means that your program doesn't close the PrintWriter before finishing the program.
For example you may have a return in a part of your program which cause that resultingSpreadsheet.close(); have not being run.

How to Write text file Java

The following code does not produce a file (I can't see the file anywhere).
What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases.
The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
In java 7 can now do
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
and w.close will be done automatically
It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.
File newFile = new File("directory", "fileName.txt");
You can do this to make a file:
newFile.createNewFile();
You can do this to make a folder:
newFile.mkdir();
Using java 8 LocalDateTime and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You can try a Java Library. FileUtils, It has many functions that write to Files.
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
The easiest way for me is just like:
try {
FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
writer.write("Wow, this is so easy!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Useful tips & tricks:
Give it a certain path:
new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
New line
writer.write("\r\n");
Append lines into existing txt
new FileWriter("log.txt");
Hope it works!

BufferedWriter not writing to .txt file even after flushing the writer

Here's the code I used, I get no errors or warnings but the file is empty, I created the aq.txt file and placed it in the workspace and it also shows in the project. I'm sure it's something stupid I'm missing but I just can't figure it out. Also, I tried all the other questions but the suggested answer is closing the stream and/or flushing it, both of which I do but they don't seem to work. Any help would be greatly appreciated!
Writer writer = null;
FileOutputStream fos= null;
try{
String xyz= "You should stop using xyz";
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getFilesDir()+File.separator+"aq.txt")));
writer.write(xyz);
writer.flush();
}
catch(IOException e) {
System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
if(writer != null){
try {
writer.close();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Try like this:
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(xyz);
writer.flush();
Context class provides a helper method Context.openFileOutput(String name, int mode) that will return a FileOutputStream to you for a file located in your applications Files directory.
I don't see any immediate reason why your way would not work, but I know I've used this other way successfully.
EDIT: After re-reading your question I think you are confused about where this file is going to be written to. It will not get written to the project folder inside of your workspace. This is going to be written to the internal storage of the android device that you run it on. Every application gets its own chunk of storage space located at \data\data\[package-name]\Files\ Your file is going to get written to there so you won't be able to immediately open it up and see the contents of it (unless your device is rooted.) You will instead have to open it up with java code and print its contents to the Log or some other output method in order to verify that your write did/did not work.
EDIT 2: Reading the file
FileInputStream in = openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Log.d("TAG", line);
This will read and output to the log the first line of the file.
This will certainly work :
File file = new File("fileName");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data to write in the file.");
writer.flush();

Reading in text file in Java

I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.
Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.
You're using a FileWriter to the file you're reading, so the FileWriter clears the content of the file. Don't read and write to the same file concurrently.
Also:
don't assume a file contains a line. You shouldn't use a do/while loop, but rather a while loop;
always close steams, readers and writers in a finally block;
catch(Exception) is a bad practice. Only catch the exceptions you want, and can handle. Else, let them go up the stack.
I'm not sure if you're looking for a way to improve your provided code or just for a solution for "Reading in text file in Java" as the title said, but if you're looking for a solution I'd recommend using apache commons io to do it for you. The readLines method from FileUtils will do exactly what you want.
If you're looking to learn from a good example, FileUtils is open source, so you can take a look at how they chose to implement it by looking at the source.
There are several possible causes for your problem:
The file path is incorrect
You shouldn't try to read/write the same file at the same time
It's not such a good idea to initialize the buffers in the constructor, think of it - some method might close the buffer making it invalid for subsequent calls of that or other methods
The loop condition is incorrect
Better try this approach for reading:
try {
String line = null;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
System.out.println(line);
dataList.add(line);
}
} finally {
if (br != null)
br.close();
}

Categories

Resources