My problem is saving documents in Netbeans. I created a program using Java in Netbeans. At first you register (at the click on register button a new user Map is created with the name of the user), then you login with your user name and your password. When you are logged in, the program displays a new window where you can create documents. You can write text in TextArea. Then when you're finished with writing your text you click on Save button and the text you've written saves in a document named after the text you've given in a jTextField. So for every different login the absolute path changes.
This is my code in submit button:
//ccc is the name of user map
String ccc = LogIn.uporabnik1;
try{
FileWriter writer = new FileWriter("C:\\Users\\ALEKS\\Documents\\NetBeansProjects\\EasyEdit\\"+ccc+"\\"+FileName+".txt");
BufferedWriter bw = new BufferedWriter (writer);
jTextArea1.write(bw);
bw.close();
jTextArea1.setText("");
jTextArea1.requestFocus();
writer.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
It looks like there is a typo with an extra space in your path.
Note that as an alternative, if you use Java 7+, you can also use the Paths utility class to generate paths without having to deal with os specific separators (\\ or /):
Path path = Paths.get("C:/Users/ALEKS/Documents/NetBeansProjects/EasyEdit/"
+ ccc + "/" + FileName + ".txt");
And to write a string to a file:
String text = jTextArea1.getText();
Files.write(path, text.getBytes("UTF-8"));
That makes your code shorter and you don't have to manually create and close the streams.
Finally, for long-ish operations, you should not use the GUI thread but use a background thread instead or you application will become unresponsive as the save operation is in progress.
Related
I have a programming mini competition tomorrow and we will be required to create our program on a flash drive given. The judges won't edit our code so it runs and I am worried that the flash drive letter will change and then my program won't be able to locate the text file it needs to read in.
I have always used paths for my flash drive like this:
FileReader file = new FileReader("E:/BPA/Crypto/input.txt");
Is there a way for me to guarantee my program will be able to read in the text file despite if the letter name for my flash drive isn't the same on the judges computer as it was on mine? Thanks!
You may
Put the file inside your sources
Use Class.getResourceAsStream(String name) to get InputStream of the file
For example, if you have class x.y.z.A
Copy input.txt to src folder into x/y/z package
Get corresponding InputStreamReader as InputStreamReader fileStream = new InputStreamReader(A.class.getResourceAsStream("input.txt"));
If you aren't sure what drive the file will be you could do something like this
char drive = 'A';
String filePath = ":/BPA/Crypto/input.txt";
while(drive != 'Z')
{
try{
Scanner readFromFile = new Scanner(new File(drive + filePath));
readFromFile.close(); //add this if you simply want the path or drvie letter
break;
}catch(FileNotFoundException error)
{
System.out.println("Drive: " + drive + " did not contained file in " + drive + filePath);
}
drive += 1;
}
Basically the idea is to attempt to open the file for reading from different drives starting at A up until Y. Obviously you can go further but I am going to assume that drives A-Y would safely exhaust all the possible drives on where ever you are running your software.
By the time you get our of the While loop the variable "drive" will contain the correct letter of the drive you want. You can modify it to be a function that returns the letter, or perhaps the file path, or simply use it once whenever you try to read from the text file. Up to you.
What I am trying to do is write a record to new line in my text file. Every time someone clicks sign up on my program, I want to call a method that opens a file and adds a record. This is what I have now:
To open the file:
try {
l = new Formatter("chineses.txt");
System.out.println("Did create");
} catch (Exception e){
System.out.println("Did not create");
}
To add the record:
public void addRecord(){
l.format("%s", nameField.getText());
}
Every time I put in a name in the name field and click sign up in my GUI, it always replaces whatever is on the first line in the text file.
How can I make it write to the second line while retaining what is on the first line?
Have you thought about using RandomAccessFile? You can seek to the end, then write.
According to the javadoc a formater created with a single String argument will first empty the file (truncate to zero length) before writing to it. This is why your file is not appended to. The program first removes whatever is in the file and then writes the new content to it when you call l.format().
What you probably want to do is format your data to a String using Formatter(). Open your record file for appending and then write that string to the file. This link should have plenty of details on how you might do this. (I googled "java open and write a file" to find that resource)
I am working on a web application in which it takes action log for every minute i.e.., any action performed will be appended into a text file with current date as its name and if no action performed then it will append current time stamp in that same file. So for everyday one new file will be created and action performed will be appended in that file for that whole day. What I want now is, all those files are present in D:\ -->(presentdate)<--.txt and when I give a particular date in the same format as that of file name in the "text field" and click on submit in my web application it has to show that file present in D drive as a hyper link(if present in the drive) and when I click on the hyperlink it should simply show the content in that file. I want to know how to search for a file in particular folder/drive without mentioning file name directly but searching for files which are having file names in specific format(Example: 27_06_2014.txt).Any suggestions will be very helpful.
Thank you.
String path = "D:" + File.pathSeparator + fileSearched + ".txt";
File f = new File(path);
if(f.exists()) {
//do your stuff
}
//I dont know why would you like to search them as a list but anyways
File dir = new File("D:");
dir.mkdir();
for(String s : dir.list()){
if(s.equalsIgnoreCase(fileSearched)){
//do your stuff
}
}
Here's the documentation for the java.io.File class
I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile is not working, and I don't understand why. Here is the basic outline of my code.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:(Lets imagine that the program looped twice before clearCondition was met)
Example Text
Example Text
Text to be written onto the first line of temp file
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.
What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.
I am developing an app, in which the user puts some numeric info in some text fields, the app is supposed to write the info into a txt file for later use, for example next time the app is opened or a refresh button is pressed the numbers should be read from the file and loaded into the same text fields so the user can change them if needed. While both "writer" and "loader" functions seem to be working, the problem is that every time "loader" is being called, it loads the data from some previously saved file and not the file that is created right now by the "writer". If the user wants the new saved data to be loaded into text fields, he needs to close and reopen the app again. To explain the situation better, I placed some scenario after the codes. Any ideas what is wrong and what can be done?
Here is the code that I'm using to put the info into the file, and it works fine:
public void writer(View view){
try {
FileOutputStream fos = openFileOutput("myfilename", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
PrintStream prntst = new PrintStream(fos);
txtEditor=(EditText)findViewById(R.id.editText1);
prntst.println (txtEditor.getText().toString());
txtEditor=(EditText)findViewById(R.id.EditText02);
prntst.println (txtEditor.getText().toString());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is the code I'm using to read the info from file to some ArrayList, then this ArrayList is used to fill up the textfields, this is also working fine (fine means without error):
public void reader(View view){
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("myfilename")));
Scanner scanner = new Scanner(inputReader);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
bld.add(line);
}
inputReader.close();
scanner.close();
txtEditor=(EditText)findViewById(R.id.editText1);
txtEditor.setText(bld.get(0));
txtEditor=(EditText)findViewById(R.id.EditText02);
txtEditor.setText(bld.get(1));
} catch (IOException e) {
e.printStackTrace();
txtEditor=(EditText)findViewById(R.id.editText1);
bld.add((txtEditor.getText().toString()));
txtEditor=(EditText)findViewById(R.id.EditText02);
bld.add((txtEditor.getText().toString()));
}
}
Scenario:
User opens the app, there are some default values in text fields (two textfields), the user changes the values to 2 and 3 respectively, and touches the save button.
User changes the values again but instead of touching the save button he hits the load button, now the app is supposed to load 2 and 3 into fields (which are saved) but instead, it loads the defaults values.
User closes the app and reopens them, this time 2 and 3 are shown as default in textfields. Seems like the "loader" NOW is reading the data from the previously saved file.
User changes the values from "2 and 3" to "13 and 14" and hits save and load button respectively, but 2 and 3 are loaded into fields.
User closes and reopens the app again, this time 13 and 14 are shown.
PS. the variable bld is global and defined in the MainActivity:
ArrayList<String> bld = new ArrayList<String>();
Thank you,
The problem may be with the global ArrayList variable 'bld'. It's OK to define it globally, But initialize it locally.
The problem is that, you are calling as bld.get(0), But the new values are appended after it.
Add the line bld = new ArrayList<String>();
inside your 'reader' function.
In the writer method you're closing the file output stream:
fos.close();
But surely you should be closing the print stream instead.
prntst.close();
Closing the print stream will flush the stream and then close the underlying output stream. When you close the output stream, it won't know anything about the print stream constructed on top of it, so won't know to flush it.