Using Java unable to save to text file - java

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!!

Related

How to write to file synchronously using 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, ...

Cannot Read File in Working Directory

I am learning basic I/O for java, and the following example is from Oracle's tutorial. The program flows a FileNotFound exception. I place the file under the working directory, and I also tried to use absolute file path, and the result is still the same. I use Eclipse to write the code. What could be causing this exception? Thanks
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
There are a lot of things that can cause that exception. Here are a few things to try:
-Verify that Xanadu.txt is a file using the isFile() method. If it returns false then you know where your problem is.
-Try placing the file in the project directory.
-Given that you already tried using the absolute file path I would also make sure that your program has permission to look at and write to the file. To check if eclipse has permission go to the properties of your file
Place the file xanadu.txt in the project directory and FileNotFoundException will go away.
FileInputStream will expect an existing input file.
The code probably isn't being executed from the path you expected.
You should use the home folder for this. C:\Users\<User Name> on windows and /home/<User Name> on linux. You can create a folder there to put your files.
To get the home directory, you can use this.
System.getProperty("user.dir")
Other solution would be to pack the files inside the JAR.
If you want to debug your problem, you can get the current directory like this.
<Your Class>.class.getProtectionDomain().getCodeSource().getLocation()

Java File Reader not finding appropriate file

I am working on a basic game similar to Break Out and I plan to use a text file to store level data on where various objects should be located when a level is rendered onto the screen. Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LevelData {
public LevelData(){
readFile();
}
public void readFile(){
try{
BufferedReader in = new BufferedReader(new FileReader("Levels"));
String str;
while((str = in.readLine()) != null){
process(str);
in.close();
}
}catch (IOException e){
System.out.println("File Does Not Exist");
}
}
private void process(String str){
System.out.println(str);
}
}
This following code, based off of previous research, should access the file "Levels" that is located in the same package as the Java class, but if the program cannot access the file then it should print "File Does Not Exist" to the console. I have created a file called "Levels" that is located in the same package as the Java class but whenever I run this class, it does not read the file properly and it catches the Exception.
Does anyone have any ideas on why it cannot access the proper file? I have already looked on various other threads and have found nothing so far that could help me.
Thanks in advance
Your Levels file probably doesn't want to be in the same package as the class, but rather, in the same directory from where your java program was run.
If you're using eclipse, this is probably the project directory.
Your issue is probably the lack of a file extension!
BufferedReader in = new BufferedReader(new FileReader("Levels.txt"));
In case you are running from Eclipse, the file should be accessed like new FileReader("src/<package>/Levels") .
Closing the inputstream in.close(); should happen outside the while loop.
As you said you plan to use a text file to store level data. One way to solve the problem is to provide relative path to the file while storing and while reading the file use the relative path to read the file. Please don't forget to specify the extention of the file.
I see a few problems, the first one being there's no file extension. Second, the in.close() is in the while loop, and since you are planning on storing high scores, I would recommend you would use an ArrayList.
It is always a good practice to specify the absolute path name of the file if the file is external to your jar file. If it is part of your jar file, then you need to get it using 'getResourceAsStream()'.

Why isn't java finding my file

Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.

Relative path to store a file in any computer - Java

I have used this reference to read a file on my project. but i need to store likewise i don't know how to do this? please help me.
for reading a file i have taken the code from the link
InputStream csv =
SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");
Like this can anyone help me with writing a file
currently I'm using this code:
Writer output = null;
output = new BufferedWriter(new FileWriter("./filename.csv"));
But it throws FileNotFound Exception at runtime
Issue is with locating file path. it works fine if i give absolute path. but it needs to be run in any computer
The FileWriter will create files as required. It doesn't have to exist already.
The only way you can get this error is if the current working directory no longer exists or you don't have permission to create a file in the directory.
Check your permissions:
Writer output = null;
if (new File("./filename.csv").canWrite()) {
System.out.println("You have not permissions");
} else {
output = new BufferedWriter(new FileWriter("./filename.csv"));
...
}
OK..Use the following code to get the path of file:
String path = System.getProperty("user.dir");
FileWriter fw = new FileWriter(path+File.separator+"filename.csv");
EDIT
Here is a Demo Code that is creating file "pqr.txt" in package myPackage. Given that I am executing the class file using command java myPackage.AccessCheck i.e from one directory above the mypackage.
package myPackage;
import java.io.FileWriter;
import java.io.File;
public class AccessCheck
{
protected void callme()
{
try
{
String name = System.getProperty("user.dir")+File.separator+AccessCheck.class.getPackage().getName()+File.separator+"pqr.txt";
System.out.println(name);
FileWriter fw = new FileWriter(name);
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
AccessCheck asc = new AccessCheck();
asc.callme();
}
}
Instead of calling getResourceAsStream(), call class.getResource() or classLoader.getResource(). These functions return a URL giving the location of the resource. If the resource is a plain file on the filesystem, the URL will be a file: URL.
Once you have the URL, you can convert it to a URI and pass it to the File constructor which takes a URI. Then you can use the File object to open the file.
Note that getResource() can return URLs that the File constructor can't deal with. For example, if the resource is found in a jar file, then the URL might look like this:
jar:file:/C:/path/to/JDK/lib/vm.jar!/java/lang/Object.class
The File constructor can't deal with URLs like this. This may or may not be a concern for you.

Categories

Resources