Overwriting a file with another file Java/processing - java

Maybe it's just me that stupid, but i can't get this to work in, only if i try it in a file where i haven't writen anything but this:
boolean runOnce = true;
File temp = new File("myPath/tempX.txt");
File test = new File("myPath/xCordLayout.txt");
if (runOnce) {
if (test.delete()) {
System.out.println("Success");
} else {
System.out.println("Failed");
}
runOnce = false;
}
if (temp.renameTo(test)) {
System.out.println("File has been renamed!");
} else {
System.out.println("ERROR");
}
The program syestem.out.println says Failed, so its the deleting part that doesn't seem to work.
if i have it in the same way, but you have to press a buttom or somethinh else, i doesn't seem to work ( i have tested the other statements, to check if there is something wrong with them but idk). Can someone help me, or tell me how to overwrite another file?

Related

while loop and printwriter only writes one line to file

I have made a code of which gets a bunch of data from different files in a folder, I have then made sure to only look for a certain kind of word in the files. Then I have made sure the code prints out the results in the console.
All the things I have done up till now works perfectly, but here comes the issue. I want the code to also print/write the information to a .txt file. This sort of works, but it only prints one of the many lines from the different files. I am completely sure that there are more that one as the console print shows at least 20 different lines containing the right word.
I am not completely sure where I have gone wrong, I have also tried to add the .flush(); right before the .close(); but it still wont work. I have also tried to add the pToDocu.close(); underneath the sc.close();, but that doesn't work either, as that doesn't even write anything, that just creates a blank file.
So in short the code is supposed to write a bunch of lines, but it only writes one.
public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#"))
{
System.out.println(s);
pTD.println(s);
pTD.close();
}
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
UPDATE
I have changed the code to now have the pTD.close(); outside of the while loop like seen below. Only issue is that the file which is created now is blank, it has no information inside it.
public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#"))
{
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You are closing the file (pTD) after the first time you write to it. You should extract the close() call from the loop and move it after it:
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#")) {
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
Remove
pTD.close();
from your while loop. You close your Print Writer after the first write
It looks like you want to commit ALL of those records to your PrintWriter. Therefore, your pTD.close(); needs to be outside of your for loop, since you declared the PrintWriter before your for loop.

How can I make this program read the entire file before returning value false?

I have a GUI asking for a word, and when the word isn't found it returns not found for every word within dictionary.txt. I'm assuming some sort of array will be used to increment every false, but I don't know exactly how to write something like that. I can see why it returns "Nothing matches" for every incorrect string. Any suggestions?
File file = new File("dictionary.txt");
Scanner inputFile = new Scanner (file);
inputFile.useDelimiter("\n");
String wordCheck = textField.getText();
while(inputFile.hasNext()) {
String dictWord = inputFile.next();
if (wordCheck.equals(dictWord)) {
JOptionPane.showMessageDialog(null, "Pie for you!");
break;
} else {
System.out.println("Nothing matches");
}
}
Store result of wordCheck.equals(dictWord) in boolean variable and decide what to show after reading whole file and yes remove break; satement.
boolea isValid = false;
while(inputFile.hasNext()) {
...
if (wordCheck.equals(dictWord)) {
isValid = true;
}
}
if (isValid)) {
JOptionPane.showMessageDialog(null, "Pie for you!");
} else {
System.out.println("Nothing matches");
}
You can add a boolean found = false; before your while loop and set found = true; inside the loop if you found something (instead of showing the message). Then display the message AFTER the loop, depending on the state of your found variable.

Undo effects of java mkdirs()

I have a situation where I need to run a "pre-check" to see if a directory is "createable". This is not a problem, just run a file.mkdirs() and see if it returns true.
The problem is that I would like to clean up after this check. This is a bit tricky, because I want to delete only those folders and subfolder that mkdirs() actually created.
Can anyone think of a clever way to do this?
I think this method does the job without you having to call mkdirs:
public static boolean canMkdirs(File dir) {
if(dir == null || dir.exists())
return false;
File parent = null;
try {
parent = dir.getCanonicalFile().getParentFile();
while(!parent.exists())
parent = parent.getParentFile();
} catch(NullPointerException | IOException e) {
return false;
}
return parent.isDirectory() && parent.canWrite();
}
Keep one array which holds name of that dirs. so when you want to delete dir you can take that array content/string/dir-name to delete.
A bit dangerous:
if (file.mkdirs()) {
long t0 = file.lastModified();
for (;;) {
long t = file.lastModified();
if (t < t0 - 1000L) { // Created longer than it's child minus 1 s?
break;
}
t0 = t;
file.delete();
file = file.getParentFile();
}
}
If my assumption that permissions are inherited in the file structure is correct, something like this should do it:
File f = new File("C:\\doesntExist\\Nope\\notHere");
File tempFile = f;
while (!tempFile.exists())
tempFile = tempFile.getParentFile();
if (!tempFile.canWrite()
&& tempFile.isDirectory()) // Copied this line from Lone nebula's answer (don't tell anyone, ok?)
System.out.println("Can't write!");
else
{
f.mkdirs();
...
}
Judging by the mkdirs() source code:
public boolean mkdirs() {
if (exists()) {
return false;
}
if (mkdir()) {
return true;
}
File canonFile = null;
try {
canonFile = getCanonicalFile();
} catch (IOException e) {
return false;
}
File parent = canonFile.getParentFile();
return (parent != null && (parent.mkdirs() || parent.exists()) &&
canonFile.mkdir());
}
If I hadn't missed something you have two options:
remeber the state of the files on the disk before calling the mkdirs(), compare it with the state after the mkdirs(), handle if necessary
extend the File class and override mkdirs() method to remember exactly which files were created. If any are created, handle them.
The latter seems like a more elegant solution which will yield less code.
UPDATE:
I strongly recommend to take in consideration david a. comment.

Text input with LWJGL

I'm looking for a solution to receive text input through LWJGL. I'm not referring to the kind of standard keyboard event input offered by LWJGL, I'm looking for the ability to receive actual lines of text input, much like the TextFields offered by AWT/Swing. I'm doing this mostly in the interest of learning, and as such, I have no interest in using a library outside of LWJGL (such as TWL).
Currently, I have something like this:
private boolean shift = false;
private void chatControls(float ticksPassed) {
while (Keyboard.next()) {
if (Keyboard.isKeyDown(Keyboard.KEY_RETURN)) {
this.ui.toggleChat();
} else if (Keyboard.isKeyDown(Keyboard.KEY_DELETE)) {
this.chatText = "";
} else if (Keyboard.isKeyDown(Keyboard.KEY_BACK) && Keyboard.getEventKeyState()) {
try {
this.chatText = this.chatText.substring(0, chatText.length() - 1);
} catch (StringIndexOutOfBoundsException e) {}
} else if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
shift = Keyboard.getEventKeyState();
} else if (Keyboard.getEventKeyState() && !jtLetter) {
if (shift) {
this.chatText += Character.toUpperCase(Keyboard.getEventCharacter());
} else {
this.chatText += String.valueOf(Keyboard.getEventCharacter());
jtLetter = true;
}
} else {
jtLetter = false;
}
this.ui.updateChat(chatText);
}
}
However, it does not manage to properly handle shift, nor any of the other special commands described above. So, what's the best thing to do?
Take a look at this file of the source code of NiftyGUI, which should contain this text handling code.
Just delete your shift handling line and add:
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && !Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))
shift=true;
before the beginning of the While loop.

Java desktop app cannot write a file on C:\ drive

I am trying to write a file on a C:\ drive, but I get an exception.
java.io.IOException: Access denied.
Code:
public class Test {
public static void main(String[] args) {
try {
StringBuilder sb = new StringBuilder(File.separator);
sb.append("index.txt");
// sb is "\\index.txt"
File f = new File(sb.toString());
boolean isCreated = f.createNewFile();
System.out.println(isCreated);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Actually, I get it, I don't have permission to write a file there, but I am quite sure it can be done somehow. If I had an applet, I'd just obtain a permission, but here, I don't know how to do it.
The probable solution may be checking if I can write a file there, but to check it I might try to write a file first adn then delete it in order to check if it is possible to write a file there, but I don't find this solution an optimal way.
The easiest way to check is to use File.canWrite().
Having said that, it looks like you're writing into the root of the drive. On Windows that's probably not a good idea, and you may want to consider writing elsewhere - e.g. a temp dir.
I have written a method, that takes a String to a directory, and checks, whether you can write a file out there:
static boolean canWrite(String folderPath) {
File file = new File(folderPath);
String new_file = "HastaLaVistaBaby";
if (file.isDirectory()) {
try {
new File(file + "\\" + new_file).createNewFile();
} catch (IOException e) {
return false;
}
new File(file + "\\" + new_file).delete();
return true;
} else {
return false;
}
}
To improve it, you may check, whether file.isFile() and get a parent directory and call this method.
This line should be:
sb.append("C:\\index.txt");
The extra backslash escapes a backslash.
Whether you hard-code a file name, like I did, or you get a file name from the user, you need the full path and file name.

Categories

Resources