How to write to file synchronously using java? - java

I just started learning Java and I was interested in the File libraries. So I kept a notepad file open called filename.txt. Now I want to write to file using Java, but I want to get the result in real time.
I.e when the java code executes the changes should be visible in the text file without closing and reopening the file.
Here my code:
import java.io.*;
class Locker
{
File check = new File("filename.txt");
File rename = new File("filename.txt");
public void checker()
{
try{
FileWriter chk = new FileWriter("filename.txt");
if(check.exists())
{
System.out.println("File Exists");
chk.write("I have written Something in the file, hooray");
chk.close();
}
}
catch(Exception e)
{
}
}
};
class start
{
public static void main(String[] args)
{
Locker l = new Locker();
l.checker();
}
}
Is it possible and if so can someone tell me how?

Simple answer: this doesn't depend on the Java side.
When your FileWriter is done writing, and gets closed, the content of that file in your file system has been updated. If that didn't happen for some reason, you some form of IOException should be thrown while running that code.
The question whether your editor that you use to look at the file realizes that the file has changed ... completely depends on your editor.
Some editors will ignore the changes, other editors will tell you "the file changed, do you want to reload it, or ignore the changes".
Meaning: the code you are showing does "synchronously" write that file, there is nothing to do on the "java side of things".
In other words: try using different editors, probably one intended for source code editing, like atom, slickedit, visual studio, ...

Related

Java - How can I more effectively "scan" a portion of my file system with this program?

I am working on part of a proof of concept program in Java for an antivirus idea I had. Right now I'm still just kicking the idea around and the details aren't important, but I want the program I'm writing to get the file paths of every file within a certain range of each other(say 5 levels apart) in the directory and write them to a text file.
What I have right now(I will include my code below) can do this to a limited extent by checking if there are files in a given folder in the directory and writing their file paths to a text file, and then going down another level and doing it again. I have it set up to do 2 levels in the directory currently and it sort of works. But it only works if there is only one item in the given level of the directory. If there is one text file it will write that filepath to another text file and then terminate. But if there's a text file and folder, it ignores the text file and goes down to the next level of directory and records the file path of whatever text file it finds there. If there are two or more folders it will always choose one in particular over the other or others.
I realize now that it's doing that because I used the wrong conditional. I used if else and should have done something else, but I'm not sure which one I should have used. However I have to do it, I want to fix it so that it branches out with each level. For example, I start the program and give it starting directory C:/Users/"Name"/Desktop/test/. Test has 2 folders and a text file in it. Working the way I want it to, it would then record the file path of the .txt, go down a level into both folders, record any .txts or other files it found there, and then go down another level into each folder it found in those two folders, record what it found there, and so on until it finished the pre-determined number of levels to go through.
EDIT: To clarify confusion over what the problem is, I'll sum it up. I want the program to write the file paths of any files it finds in each level of the directory it goes through in another text file. It will do this, but only if there is one file in a given level of directory. If there is just one .txt for example, it will write the file path of that .txt to the other text file. But if there are multiple files in that level of directory(for example, two .txts) it will only write the file path of one of them and ignore the other. If there's a .txt and a folder, it ignores the .txt and enters the folder to go to the next level of directory. I want it to record all files in a given location and then branch into all the folders in that same location.
EDIT 2: I got the part of my code that gets the file path from this question( Read all files in a folder ) and the section that writes to my other text file from this one( How do I create a file and write to it in Java? )
EDIT 3: How can I edit my code to have recursion, as #horatius pointed out that I need?
EDIT 4: How can I edit my code so that it doesn't need a hard coded starting file path to work, and can instead detect the location of the executable .jar and use that as its starting directory?
Here is my code:
public class ScanFolder {
private static final int LEVELS = 5;
private static final String START_DIR = "C:/Users/Joe/Desktop/Test-Level1/";
private static final String REPORT_FILE = "C:/Users/Joe/Desktop/reports.txt";
public static void main(String[] args) throws IOException {
try (PrintWriter writer = new PrintWriter(REPORT_FILE, "UTF-8");
Stream<Path> pathStream = Files.walk(Paths.get(START_DIR), LEVELS)) {
pathStream.filter(Files::isRegularFile).forEach(writer::println);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Thanks in advance
If you are using Files.walk(...) it does all the recursion for you.
Opening and writing to the PrintWriter will truncate your output file each time it is opened/written to, leaving just the last filename written.
I think something like the below is what you are after. As you progress, rather than writing to a file, you may want to put the found Path objects into an ArrayList<Path> or similar for easier later processing, but not clear from your question what requirements you have here.
public class Walk
{
public static void main(String[] args) throws IOException {
try (PrintWriter writer = new PrintWriter("C:/Users/Joe/Desktop/reports.txt", "UTF-8")) {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
writer.println(filePath);
}
});
}
}
}
Here is an improved example that you can use to limit depth. It also deals with properly closing the Stream returned by Files.walk(...) that the previous example did not, and is a little more streams/lambda idiomatic:
public class Walk
{
// Can use Integer.MAX_VALUE for all
private static final int LEVELS = 2;
private static final String START_DIR = "C:/Users/Joe/Desktop/test";
private static final String REPORT_FILE = "C:/Users/Joe/Desktop/reports.txt";
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(REPORT_FILE, "UTF-8");
Stream<Path> pathStream = Files.walk(Paths.get(START_DIR), LEVELS)) {
pathStream.filter(Files::isRegularFile).forEach(writer::println);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}

Java string (source code) to show in browser

I am programming a Java application that inspects the source code of a webpage an shows that webpage to me in my default browser when a condition in the source code is satisfied.
I get my source code the following way:
String source = getUrlSource(myURL);
To show a specific webpage I know I can use:
java.awt.Desktop.getDesktop().browse(myURI);
But this is not enough for my application because of variable content, How can I get java to show me the webpage that is encoded in the string source? I need the equivalent of something that would look like
java.awt.Desktop.getDesktop().browse(sourceCodeString).
Update: If the condition is not satisfied, it will reload the same page. So the complete program executes on 1 url. Java is probably not the right language for that purpose, maybe someone has a better language to do this behaviour>
Thanks for your help,
You can save the string in a file and open the file.
public class Test {
public static void main(String[] args) throws IOException {
String html = "<html><body>Hello Browser</body></html>";
File file = new File("test.html");
FileWriter writer = new FileWriter(file);
writer.write(html);
writer.close();
Desktop.getDesktop().browse(file.toURI());
}
}

How to open a file without saving it to disk

My Question: How do I open a file (in the system default [external] program for the file) without saving the file to disk?
My Situation: I have files in my resources and I want to display those without saving them to disk first. For example, I have an xml file and I want to open it on the user's machine in the default program for reading xml file without saving it to the disk first.
What I have been doing: So far I have just saved the file to a temporary location, but I have no way of knowing when they no longer need the file so I don't know when/if to delete it. Here's my SSCCE code for that (well, it's mostly sscce, except for the resource... You'll have to create that on your own):
package main;
import java.io.*;
public class SOQuestion {
public static void main(String[] args) throws IOException {
new SOQuestion().showTemplate();
}
/** Opens the temporary file */
private void showTemplate() throws IOException {
String tempDir = System.getProperty("java.io.tmpdir") + "\\BONotifier\\";
File parentFile = new File(tempDir);
if (!parentFile.exists()) {
parentFile.mkdirs();
}
File outputFile = new File(parentFile, "template.xml");
InputStream inputStream = getClass().getResourceAsStream("/resources/template.xml");
int size = 4096;
try (OutputStream out = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[size];
int length;
while ((length = inputStream.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
inputStream.close();
}
java.awt.Desktop.getDesktop().open(outputFile);
}
}
Because of this line:
String tempDir = System.getProperty("java.io.tmpdir") + "\\BONotifier\\";
I deduce that you're working on Windows. You can easily make this code multiplatform, you know.
The answer to your question is: no. The Desktop class needs to know where the file is in order to invoke the correct program with a parameter. Note that there is no method in that class accepting an InputStream, which could be a solution.
Anyway, I don't see where the problem is: you create a temporary file, then open it in an editor or whatever. That's fine. In Linux, when the application is exited (normally) all its temporary files are deleted. In Windows, the user will need to trigger the temporary files deletion. However, provided you don't have security constraints, I can't understand where the problem is. After all, temporary files are the operating system's concern.
Depending on how portable your application needs to be, there might be no "one fits all" solution to your problem. However, you can help yourself a bit:
At least under Linux, you can use a pipe (|) to direct the output of one program to the input of another. A simple example for that (using the gedit text editor) might be:
echo "hello world" | gedit
This will (for gedit) open up a new editor window and show the contents "hello world" in a new, unsaved document.
The problem with the above is, that this might not be a platform-independent solution. It will work for Linux and probably OS X, but I don't have a Windows installation here to test it.
Also, you'd need to find out the default editor by yourself. This older question and it's linked article give some ideas on how this might work.
I don't understand your question very well. I can see only two possibilities to your question.
Open an existing file, and you wish to operate on its stream but do not want to save any modifications.
Create a file, so that you could use file i/o to operate on the file stream, but you don't wish to save the stream to file.
In either case, your main motivation is to exploit file i/o existingly available to your discretion and programming pleasure, am I correct?
I have feeling that the question is not that simple and this my answer is probably not the answer you seek. However, if my understanding of the question does coincide with your question ...
If you wish to use Stream io, instead of using FileOutputStream or FileInputStream which are consequent to your opening a File object, why not use non-File InputStream or OutputStream? Your file i/o utilities will finally boil down to manipulating i/o streams anyway.
http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
No need to involve temp files.

Using Java unable to save to text file

I'm trying to get my submit button to save the GUI in a text file, I've made the GUI and the button listener ...etc but I'm having trouble making the method that saves the information from the GUI into a text file.
so far i have:
public void save() {
File k1 = new File("documents/"+"newfile.txt");
try {
k1.createNewFile();
FileWriter kwriter = new FileWriter(k1);
BufferedWriter bwriter = new BufferedWriter(kwriter);
bwriter.write(txtField1.getText().trim());
bwriter.newLine();
bwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
but it doesn't seem to work, nothing happens; is there anything I'm missing?
You're file is called .txt - perhaps insert a name in the first row:
File k1 = new File("documents/filename.txt");
You should be getting an error when running that code.
The problem is that the document directory doesn't exist or it is not where you expected.
You can check for the parent directory with:
if(!k1.getParentFile().exists()){
k1.getParentFile().mkdirs();
}
Alternatively you need to set the file to be a more precise location.
org.apache.commons.lang.SystemUtils might be able to help you out here with user home.
i was just think is there a easier way, for example i already have the Jfilechoser open a "save as box" when the "submit" button is pressed so is there a easier way to create the file (saving the gui infomation in a txt file) ?
This is a continuation on your previous question. You should just get the selected file and write to it with help of any Writer, like PrintWriter.
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println(txtField1.getText().trim());
writer.flush();
} finally {
writer.close();
}
Don't overcomplicate by creating a new File() on a different location and calling File#createFile(). Just writing to it is sufficient.
See also:
Java IO tutorial
update here's an SSCCE, you can just copy'n'paste'n'compile'n'run it.
package com.example;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) throws IOException {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println("Hello");
writer.flush();
} finally {
writer.close();
}
Desktop.getDesktop().open(file);
}
}
}
My guess is that the file is being created, but not in the directory that you expect. Check the value of the user.dir system property and see what it shows. This is the current working directory of your JVM.
You may need to either:
Specify a full path in the code (as Martin suggested), e.g. new File("/home/foo/newfile.txt")
Change the working directory of the JVM. The way that you do this depends on how you are launching it (e.g. if you are running the java command directly from a CLI, then just switch directories first, if you are running from an IDE then change the launch configuration, etc.).
As far as I know, you cannot change the working directory at runtime (see this SO question).
Your code is working for me with minor change.
As a debugging process, I would completely delete the directory path and try to use a file only..
instead of
File k1 = new File("documents/"+"newfile.txt");
use
File k1 = new File("newfile.txt");
Check where your file is generated and then create directory there..
Good luck!!

open temp file in java

I'm writing string to temporary file (temp.txt) and I want that file should open after clicking button of my awt window it should delete when I close that file (after opening that file), how can I do this?
This is the code that I have been using to create temporary file in Java:
File temp = File.createTempFile("temp",".txt");
FileWriter fileoutput = new FileWriter(temp);
Bufferedwriter buffout = new BufferedWriter(fileoutput);
A file created by:
File temp = File.createTempFile("temp",".txt");
Will not be deleted, see javadoc, you have to call
temp.deleteOnExit();
so the JVM will delete the file on exit...
How about something like:
if (!temp.delete())
{
// wasn't deleted for some reason, delete on exit instead
temp.deleteOnExit();
}
Some links that might help you:
File.getAbsoluteFile()/getAbsolutePath().
FileReader.
File.delete().
To perform an operation when clicking a button, you will need code something like this:
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent event) {
fileOperation();
}
}
...
private void fileOperation() {
... do stuff with file ...
}
You can probably find many examples with google. Generally the anonymous inner class code should be short and just translate the event and context into operations meaningful to the outer class.
Currently you need to delete the file manually with File.delete after you have closed it. If you really wanted to you could extends, say, RandomAccessFile and override close to delete after the close. I believe delete-on-close was considered as a mode for opening file on JDK7 (no idea if it is in or not).
Just writing to a file, as in your code, would be pointless. You would presumably want to delete the file after closing a read stream no the write stream. It's not a bad idea to avoid temporary files if you possibly can.

Categories

Resources