File is being recreated even though it already exists - java

How does this code delete the file I had and makes a new one??
public void actualizaJTextArea(String cliente){
mensagens.setText("");
Scanner scanner = null;
File file = createFile(cliente + "chatswith.txt");
try {
scanner = new Scanner(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(...)
scanner.close();
}
public static File createFile(String s){
File file = new File(s);
if(!file.exists()){
try {
boolean b = file.createNewFile();
System.out.println(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
Does the method createNewFile() do this?
Thanks and I'm sorry if this has been asked before I just can't find it.
EDIT
I am also using createFile() in here to write in it but the use is the same so i guess that can't be it:
public void recebeMensagem(boolean b){
while(true){
Mensagem m = null;
try {
m = (Mensagem)input.readObject();
System.out.println("Mensagem Recebida:"+m);
} catch (ClassNotFoundException e){
} catch (IOException e) {
try {
input.close();
System.out.println("Server desligou...");
break;
} catch (IOException e1) {
}
}
if(m != null){
for(Mensagens mensagens:v){
for(String string: m.getReceivers()){
if (mensagens.getCliente().equals(m.getAuthor()) && mensagens.getContacto().equals(string)){
mensagens.actualizaJTextArea(cliente);
}
}
}
for(String Str :m.getReceivers()){
PrintWriter p = null;
File file = Mensagens.createFile(cliente + "chatswith.txt");
try {
p = new PrintWriter(new FileWriter(file));
p.append(m.getAuthor()+"</<"+Str+"</<"+m.getText()+"\n");
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

createNewFile() is atomic and it will not delete the file if it is present. Please look at the boolean output, it should be false if your file exists already.
EDIT
add append parameter to FileWriter. It is overwriting every time.
FROM
p = new PrintWriter(new FileWriter(file));
TO
p = new PrintWriter(new FileWriter(file,true));

Related

Java: How to delete a file

In the code below how come when it say that it has successfully deleted the file, but when I check the file is still there. How would I remove the file. Basically I'm trying the delete the first file that I made after I was done using it to create the second file.
public static void main(String[] args) {
File file = new File("Hello");
try {
file.createNewFile();
} catch (Exception e) { }
try {
PrintWriter e = new PrintWriter(file);
e.println("Hello hi");
e.close();
}catch (Exception e) {}
File file2 = new File("Hello2");
try {
file2.createNewFile();
} catch (Exception e) {}
try {
Scanner x = new Scanner(file);
PrintWriter e = new PrintWriter(file);
while (x.hasNextLine()) {
System.out.println("Hello");}
e.close();
} catch (Exception e) {}
try {
file.delete();
System.out.println("It was deleted");
} catch (Exception e) { }
}
}
file.delete() doesn't throw an IOException, it returns a boolean check into if condition
if(file.delete())
{
System.out.println("File deleted successfully");
}
else
{
System.out.println("Failed to delete the file");
}

Java unreported exception confusing me

Hey guys I've been working on some buttons for my GUI, and I decided to implement some previous code.
However, I'm getting an error when I try to compile. In line 141 in my code (specifically, the last button) I am told that I have an unreported IOException that must be caught or declared to be thrown.
My code is below:
public void actionPerformed(ActionEvent ae) {
if ((ae.getSource() == button5) && (!connected)) {
try {
s = new Socket("127.0.0.1", 2020);
pw = new PrintWriter(s.getOutputStream(), true);
} catch (UnknownHostException uhe) {
System.out.println(uhe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
connected = true;
t = new Thread(this);
//b.setEnabled(false);
button5.setLabel("Disconnect");
t.start();
} else if ((ae.getSource() == button5) && (connected)) {
connected = false;
try {
s.close(); //no buffering so, ok
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
//System.exit(0);
button5.setLabel("Connect");
} else {
temp = tf.getText();
pw.println(temp);
tf.setText("");
}
if (ae.getActionCommand().equals("Save it")) {
Scanner scan = new Scanner(System.in);
try {
PrintWriter pw = new PrintWriter(new FileWriter(new File("test.txt")));
for (;;) {
String temp = scan.nextLine();
if (temp.equals("")) {
break;
}
pw.println(temp);
}
pw.close();
} catch (IOException ioe) {
System.out.println("IO Exception! " + ioe.getMessage());
}
} else if (ae.getActionCommand().equals("Load it")) {
Scanner scan = new Scanner(System.in);
try {
BufferedReader br = new BufferedReader(new FileReader(new File("test.txt")));
String temp = "";
while ((temp = br.readLine()) != null) {
System.out.println(temp);
}
br.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Input file not found.");
} catch (IOException ioe) {
System.out.println("IO Exception! " + ioe.getMessage());
}
} else if (ae.getActionCommand().equals("Clear it")) {
ta.setText("");
} else {
PrintWriter pw = new PrintWriter(new FileWriter(new File("test.txt")));
}
}
just add a try/catch block to the following code (end of what you posted):
else{
PrintWriter pw = new PrintWriter (
new FileWriter(
new File("test.txt")));
}}
like so:
else{
try{
PrintWriter pw = new PrintWriter (new FileWriter(new File("test.txt")));
} catch (Exception e) {
e.printStackTrace();
}
}}
In general, any IO operation can potentially cause an exception. Depending on what you want, the easiest solution is just put throws IOException at the top of the method where you see the problem, but this isn't very good practice, and doesn't work in this case. Putting a try/catch block around the problem line, and including a meaningful error message, is probably the best way to go.

Write Integer Value to a File and Read it

I got a Follower-check function in my twitch.bot and i need a read/write solution for it.
It should do the following:
Read an given Number(int) out of the file
Write a new Number to the file and delete the old one
Create the file if it doesnt exist
(the File needs only to store 1 number)
So how can i do this?
right now, i got a String Reader and as soon as i read it i parse it into an INT but i only got errors so i think it doesnt work that way so im searching an option for writing/reading the int already without parsing it from a string.
import java.io.*;
public class FollowerChecker {
public static StringBuilder sb;
static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public static void Writer() {
FileWriter fw = null;
try {
fw = new FileWriter("donottouch.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringWriter sw = new StringWriter();
sw.write(TwitchStatus.totalfollows);
try {
fw.write(sw.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It appears to be way more complicated than it should be. If you just want to write a number without parsing it as text you can do this.
BTW You may as well use a long as it will use the same disk space and store more range.
public static void writeLong(String filename, long number) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
dos.writeLong(number);
}
}
public static long readLong(String filename, long valueIfNotFound) {
if (!new File(filename).canRead()) return valueIfNotFound;
try (DataInputStream dis = new DataInputStream(new FieInputStream(filename))) {
return dis.readLong();
} catch (IOException ignored) {
return valueIfNotFound;
}
}

Java: Read/Write a File and more

I made a Class with 2 Methods which should handle either Writing in a file or reading from it.
Ive came up with something like this:
package YBot;
import java.io.*;
public class FollowerChecker {
public static StringBuilder sb;
static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public static void Writer() {
FileWriter fw = null;
try {
fw = new FileWriter("donottouch.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringWriter sw = new StringWriter();
sw.write(TwitchStatus.totalfollows);
try {
fw.write(sw.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now My Question is:
How can i add the function to create the "donottouch.txt" file if it doesnt exist already or if its empty to write "0" in it? when my program starts it will read the file for a number and later, if the number is changed it will rewrite it. so it would be the best that as soon it trys to read and its not there, it creates it right then and reread it. hope some1 can give me any examples =)
Here is how I handled it:
public static boolean checkIfExists(String path) {
if (!new File(path).exists()) {
return false;
} else {
return true;
}
}
public static String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line;
StringBuilder sb = new StringBuilder();
while( ( line = reader.readLine() ) != null) {
sb.append( line );
}
reader.close();
return sb.toString();
}
public static void writeFile(String path) throws FileNotFoundException,
UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.println("0");
writer.close();
return;
}
public static void main(String args[]) {
/*Gets absolute path to your project folder, assuming that is where
* you are storing this text file. Otherwise hard code your path
* accordingly.
*/
File file = new File("");
String fileGet = file.getAbsolutePath();
StringBuilder sb = new StringBuilder();
String path = sb.append(fileGet.toString() + "/donottouch.txt").toString();
String result=null;
if(!checkIfExists(path)) {
try {
writeFile(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("File created: 'donottouch.txt'");
} else {
try {
result = readFile(path);
} catch (IOException e) {
e.printStackTrace();
}
if( result.length() == 0 ) {
try {
writeFile(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("File amended: 'donottouch.txt'");
}
System.out.println("File exists: 'donottouch.txt'");
}
}
Obviously I created a main class and did all of this outside of a class, unlike you, but it should be very simple to integrate. It is predicated on the presumption that you are storing your "donottouch.txt" in the source file of the project, however you can easily change the piece of code that grabs your absolute path to the hardcoded path of the folder in which you are looking. Hope this helps!

Extracting a file with JUnrar

I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}

Categories

Resources