Unable to modify a file entered as an argument JAVA - java

I'm trying to get this to work but it doesn't and I don't get why,
It's supposed to be a script where I enter an argument file and it replaces it with the correct replaced characters in it.
It doesn't replace the file I entered as argument.
I can get it to work If I place the whole code in the main function without calling a method.
Thanks.
public class Rename
{
public static void main(String[] args) throws IOException{
File origine = new File(args[0]);
renameFile(origine);
}
public static void renameFile(File fileOriginal) throws IOException
{
try
{
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(fileOriginal);
BufferedReader br = new BufferedReader(fr);
while (br.ready())
{
fw.write(br.readLine().replace("#/A#" , "Á"));
}
fw.close();
br.close();
fr.close();
tempFile.renameTo(fileOriginal);
} catch (IOException e) {
e.printStackTrace();
}
}
}

renameTo() returns a value. You are ignoring it.
You can't rename a file to the name of an existing file. You have to ensure the target name doesn't exist.
ready() is not a test for end of stream: see the Javadoc.
A method that modifies the content of a file should not be called renameFile().

Related

Comparing ArrayList with user input

I have been trying to compare the file content with user input. The program is reading from a specific file and it checks against the user's string input. I am having trouble comparing the ArrayList with the user input.
public class btnLoginListener implements Listener
{
#Override
public void handleEvent(Event arg0)
{
//variables for the class
username = txtUsername.getText();
password = txtPassword.getText();
MessageBox messageBox = new MessageBox(shell, SWT.OK);
try {
writeFile();
messageBox.setMessage("Success Writing the File!");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when writing the file!");
}
try {
readFile("in.txt");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when reading the file!" + x);
}
if (username.equals(names))
{
messageBox.setMessage("Correct");
}
else
{
messageBox.setMessage("Wrong");
}
messageBox.open();
}
}
private static void readFile(String fileName) throws IOException
{
//use . to get current directory
File dir = new File(".");
File fin = new File(dir.getCanonicalPath() + File.separator + fileName);
// Construct BufferedReader from FileReader
BufferedReader br = new BufferedReader(new FileReader(fin));
String line = null;
while ((line = br.readLine()) != null)
{
Collections.addAll(names, line);
}
br.close();
}
I am assuming you are trying to check whether an element exists in the list. If yes, then you need to use contains method, here's the Javadoc.
So, instead of using if (username.equals(names)), you can use if (names.contains(username)).
Apart from this, you should make the following changes:
Don't read the file every time an event is called. As you are reading a static file, you can read it once and store it in an ArrayList.
Make variables username and password local.
Remove writeFile() call unless it's appending/writing dynamic values on each event.

Getting contents of WriteTo File in a subclass

Here I have this code shortened to show the most important methods in question: The method void writeToFile(string filename) is in my superclass called "Words"
public void writeToFile(String filename) throws IOException {
FileWriter out = null;
try {
File outFile = new File(filename);
out = new FileWriter(outFile);
out.write("Writing to a text file");
}
catch(IOException e) {
System.err.println(e.getMessage());
}
finally {
if(out != null) { out.close(); }
}
}
I also have this method below in my concrete sub class which creates a file with a given name:
public Vowels makeVowels(String filename) throws IOException, InvalidSequenceException {
writeToFile("vowels.txt");
Vowels vowel = new Vowels(this.getDescription("vowels.txt"), this.getContent("vowels.txt"));
return vowel;
}
If I call the method writeToFile("vowels.txt") from my subclass to create a new file this does not create the file ? How can I call the writeToFile method from my subclass to create this vowels.txt file ?
I found the solution was to move the writeToFile("vowels.txt") from my vowels method to a different place such as in my constructor or creating a new method and calling this writeToFile("vowels.txt") works. Also as suggested by Robertos Attias using System.out.println(System.getProperty("user.dir")); showed the current directory.

Cannot Write String to FileWriter/BufferedWriter

I am trying to make an application that will create Google Authenticator secret keys, as well as authenticate the OTP. I am writing all of my passwords to individual files titled with the name that goes along with them.
First and foremost, I am using this library.
https://github.com/aerogear/aerogear-otp-java
This is my code:
public void createUserFile(String name) throws IOException
{
File file = new File("users\\" + name + ".txt");
file.createNewFile();
}
public void generateUserKey(String name)
{
try
{
File file = new File("users\\" + name + ".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fw);
String s = Base32.random();
out.write(s);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
If I change the value of s to something like "Hello" I am fine. However, it will not write that random string. That is what I need help with. I have tinkered and searched hours for answers, and I have found nothing.
I don't believe you need createUserFile, and it isn't clear you necessarily know where the "users/" folder (a relative path) is. I suggest you use System.getProperty(String) to get user.home (the User home directory).
I would also suggest you use a try-with-resources Statement and a PrintStream. Something like
public void generateUserKey(String name) {
File file = new File(System.getProperty("user.home"), //
String.format("%s.txt", name));
try (PrintStream ps = new PrintStream(file)) {
ps.print(Base32.random());
} catch (IOException e) {
e.printStackTrace();
}
}

JDK 7: Existing file gets empty on new File("path/to/file.html");

I'm using JDK 7. I've got a class with a method that creates a html-file using PrintStream. Another method in the same class is supposed to use the created file and do stuff with it. The problem is that once i use new File("path/to/file.html), the file lenght is reduced to 0. My code:
public class CreatePDFServiceImpl {
private final PrintStream printStream;
public CreatePDFServiceImpl() throws IOException {
printStream = new PrintStream("/mnt/test.html", "UTF-8");
}
public void createHtmlFile() throws IncorporationException {
try {
StringBuilder html = new StringBuilder();
HtmlFragments htmlFragments = new HtmlFragments();
html.append(htmlFragments.getHtmlTop())
.append(htmlFragments.getHeading())
.append(htmlFragments.buildBody())
.append(htmlFragments.buildFooter());
printStream.print(html.toString());
} finally {
if(printStream != null) {
printStream.close();
}
}
}
This next method is supposed to use the html file created in "createHtmlFile()":
public void convertHtmlToPdf() {
PrintStream out = null;
try {
File file = new File("/mnt/test.html");
/** this code added just for debug **/
if (file.createNewFile()){
System.out.println("File is created!");
} else {
System.out.println("File already exists. size: " + file.length());
}
/* PDF generation commented out. */
//out = new PrintStream("/mnt/testfs.pdf", "UTF-8");
//defaultFileWriter.writeFile(file, out, iTextRenderer);
} catch (IOException e) {
throw new IncorporationException("Could not save pdf file", e);
} finally {
if(out != null) {
out.close();
}
}
My junit integration test class:
#Category(IntegrationTest.class)
public class CreatePDFServiceIntegrationTest {
private static CreatePDFServiceImpl createPDFService;
#BeforeClass
public static void init() throws IOException {
createPDFService = new CreatePDFServiceImpl();
}
#Test
public void testCreateHtmlFile() throws IncorporationException {
createPDFService.createHtmlFile();
File createdFile = new File("/mnt/test.html");
System.out.println("createdFile.length() = " + createdFile.length());
Assert.assertTrue(createdFile.length() > 1);
}
#Test
public void testCreatePDF() throws Exception {
File fileThatShouldExist = new File("/mnt/testfs.pdf");
createPDFService.convertHtml2Pdf();
Assert.assertTrue(fileThatShouldExist.exists());
}
}
The first test passes, output:
"createdFile.length() = 3440".
I checked the file system, there is the file. size 3,44kb.
Second test fails, output from CreatePDFServiceImpl:
"File already exists. size: 0"
Looking in the file system, the file now is actually 0 bytes.
I'm stumped. The new File("path") should only create a reference to that file and not empty it?
I doubt there's an error in File.createNewFile(). I don't yet fully grasp in which order you run your code, but are you aware that this sets the file size to zero?
out = new PrintStream("/mnt/testfs.pdf", "UTF-8");
From the PrintStream(File file) Javadoc:
file - The file to use as the destination of this print stream. If the
file exists, then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
I think that's the culprit - but in your code that line is commented out. Am I right you have run your tests with that line commented in?

How to know if an agument is a directory or file in Java

I am trying to pass an argument to a method . The argument can be a file or a direcotry.
public class ReadCsv {
String line = null;
BufferedReader br ;
public void readCsv(String arg) throws Exception{
File file = new File(arg);
if(file.isDirectory()){
for(File dir : file.listFiles()){
System.out.println(file.getName());
reader(dir);
}
}
else{
reader(file);
}
}
public void reader(File file) throws Exception {
br = new BufferedReader(new FileReader(file));
while((line=br.readLine())!=null){
//Code
}
}
But the code is not working as I want to. When I pass an argument arg , I have to determine whether it is a file or a directory and work according to it . Can anyone please help me how to determine a file or a directory .This code of mine runs the loop 4 times if arg is a directory.
Your code looks fine, looks like you're just outputting the directory (which you have named 'file') instead of the file, which you have named 'dir'.
for(File dir : file.listFiles()) {
System.out.println(dir.getName()); //you were outputting file.getName()
}
File has isDirectory() and isFile() methods you can use to check the type.
See File official documentation. There are methods such as:
isFile();
isDirectory();
Try It ..
It print all Directories and file name .
IF Nested Directories :
public class ReadCsv {
String line = null;
BufferedReader br ;
public void readCsv(String arg) throws Exception{
File file = new File(arg);
checkIsDir(file );
}
public void checkIsDir(File file) throws Exception {
if(file.isDirectory()){
System.out.println("Directory : "file.getName());
for(File dir : file.listFiles()){
checkIsDir(dir);
}
}
else{
System.out.println("File : "file.getName());
reader(file);
}
}
public void reader(File file) throws Exception {
br = new BufferedReader(new FileReader(file));
while((line=br.readLine())!=null){
//Code
}
}

Categories

Resources