File contents reset when file exists already

	private void initFiles() throws IOException {
		String path = Main.class.getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		String decodedPath = URLDecoder.decode(path, "UTF-8");

		File clientConfig = new File(decodedPath + "clientConfig.cfg");
		boolean existed = true;

		if (!clientConfig.exists()) {
			clientConfig.createNewFile();
			existed = false;
		}

		BufferedWriter cfgWriter = new BufferedWriter(new FileWriter(
				clientConfig));

		if (!existed) {
			cfgWriter.write("127.0.0.1:10008");
		    cfgWriter.flush();
		}

		BufferedReader cfgReader = new BufferedReader(new FileReader(
				clientConfig));

		String serverInfo[] = cfgReader.readLine().split(":");

		host = serverInfo[0];
		port = Integer.parseInt(serverInfo[1]);

		cfgReader.close();
		cfgWriter.close();
	}

I believe that the title should be self explanatory, when I execute the jar without the clientConfig.cfg it works fine, but when it exists already its contents are reset and that causes the rest of the code to stop working

Because when you open it with the buffered writer you override your file with an empty one.

You should use NIO2 to have more controll, i.e. :


        Path a = Paths.get("file.xyz");
        Files.newBufferedWriter(a, Charset.defaultCharset(), StandardOpenOption.TRUNCATE_EXISTING);

there are other options which create new file everytime or only if it does not exist already and so on

I don’t believe NIO2 is the answer here. If he doesn’t want to write anything, he shouldn’t open a file for writing. Move the FileWriter code inside the [icode]if(!existed)[/icode] block.

Thanks Riven!