First of all I am iMacros scripts writer.
This is java function for writing a file (not fully complete but you will get the idea)
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
Now bellow is java function used in JavaScript to do the same task as the function above and I run that .js file in iMacros. Works like a charm.
//Function to write the file
function writeFile(filename, data)
{
try
{
//write the data
out = new java.io.BufferedWriter(new java.io.FileWriter(filename, true));
out.newLine();
out.write(data);
out.close();
out=null;
}
catch(e) //catch and report any errors
{
alert(""+e);
}
}
Now I need a java function that will create file and folder on Hard Drive location and I found this.
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main( String[] args )
{
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
But now I need java function that will create folder and an empty file (with different extensions like .txt .csv etc.) and the function will work in JavaScript.
Can anyone give me some guide lines from the two examples above? How can I write a functions in Java and run it in JavaScript?
I won't claim to fully understand the question, but this is how to make sure some directory exists, and to create a random file in it:
// make the dir and ensure the entire path exists
File destinationDir = new File("c:\\whereever\you\want\that\file\to\land").mkdirs();
// make some file in that directory
File file = new File(destinationDir,"whateverfilename.whateverextension");
// continue with your code
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
This function is used in iMacros .js file. It is a Java method called in JavaScript.
createFile("C:\\testingfolder","test.csv");
function createFile(folder,file)
{
destinationDir = new java.io.File(folder).mkdirs();
file = new java.io.File(folder,file);
file.createNewFile();
}
The function creates folder and in it creates a file.
Related
When I write an FileInputStream, while I have the valid file, it throws a FileNotFoundException.
I used this:
package io;
import java.io.*;
public class implementIo {
public static int i;
public static FileOutputStream output;
public static FileInputStream input;
public static void main(String args[]) {
try {
output = new FileOutputStream("writeModification.txt");
input = new FileInputStream("modification.txt");
do {
i = input.read();
if(i != -1) output.write(i);
}while(i != -1);
} catch (Exception e) {
System.out.println("Exception caught " + e);
} finally {
try {
if(output == null) input.close();
}catch(IOException e) {
System.out.println("IOException caught: " + e);
}
}
}
}
While I had a two separate files named "modification.txt" and "printModification.txt" in the same package folder, yet the system threw a FileNotFoundException. Please help!
This is because the FileInputStream doesn't provide the file creation during initialization like new FileOutputStream() does. So if these have been said, we can see one interesting thing to keep in mind: the modification.txt will be created every time when you initialize the FileOutputStream (and won't be overwritten) and this is why most probably your code breaks at the new FileInputStream() line.
How can you handle your exception?
You either create your file before executing the code( manually with New -> Text Document etc. ) or modify your code and make use of File class :
File file = new File("modification.txt");
try {
file.createNewFile();
input = new FileInputStream(file);
//your code here - output etc.
Your code still doesn't work even if you have the files created in the same package folder? It's because the default path that your streams are looking for your files is the current working directory. Here is an example :
myproject
|___src
| |___main
| |___java
| |___io
| |___implementIo
|___writeModification.txt
|___modification.txt
This is the correct structure if you want to use the streams like you did (with just a simple file name in stream constructor argument). But if your files are not there, you have to specify the absolute path. Here is an example :
myproject
|___src
|___main
|___java
|___io
|___implementIo
|___writeModification.txt
|___modification.txt
And the correct way to access the files is this:
FileInputStream input = new FileInputStream("C://myproject//src//main//java//io//modification.txt");
Same for the output stream. (Please modify the path with your correct file location)
When I use my program within Eclipse everything works flawlessly, the JSON file is saved between launches. The problem occurs when i export the project to a Runnable Jar File, the saving of the JSON file no longer works, at all. I can still read from the file, but it doesn't save it.
Here is the "writing/saving" code I've written.
/*
* Write to character JSON file
*/
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
Since outside Eclipse neither the bin nor the file itself haven't been created yet, you have to create it, at first and if there was a file before, since we want to overwrite it, we use the delete method before creating it. So the whole changes are written here:
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
file.getParentFile().mkdirs();
file.delete();
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
I tested it and the way to make the jar to create new folders is to execute it from the windows command console with:
java -jar jarName.jar
Or to create a bat file on the same folder.
I am trying to create a temporary file and then rename it to a usable file. The temp file is getting created in %temp% but not getting renamed:-
static void writeFile() {
try {
File tempFile = File.createTempFile("TEMP_FAILED_MASTER", "");
PrintWriter pw = new PrintWriter(tempFile);
for (String record : new String[] {"a","b"}) {
pw.println(record);
}
pw.flush();
pw.close();
System.out.println(tempFile.getAbsolutePath());
File errFile = new File("C:/bar.txt");
tempFile.renameTo(errFile);
System.out.println(errFile.getAbsolutePath());
System.out.println("Check!");
} catch (Exception e) {
e.printStackTrace();
}
}
There are a few reasons why a rename can fail. The common ones are:
You don't have write permission for the source or destination directory.
The file you are renaming is open (on Windows)
You are attempting to rename across different file systems.
It can be difficult to diagnose these (and other) failure reasons if you are using File.renameTo because all you get is a boolean return value.
I recommend using Files.move instead. It can cope with moving files between file systems, and will throw an exception if the file cannot be renamed.
I have tried and succeed moving files from one folder to another folder using java . Here is my code
File source = new File("D:\\polo\\");
File desc = new File("E:\\polo2\\");
try {
FileUtils.copyDirectory(source, desc);
} catch (IOException e) {
e.printStackTrace();
}
But i would like to move specific files from one folder to the other not all the files. Is this possible to do in java. Please help us on this
You can use Java SE standard utility
java.nio.file.Files.copy(Path source, Path target, CopyOption... options)
use renameTo
public static void main(String[] args)
{
try{
File source = new File("D:\\polo\\");
File desc = new File("E:\\polo2\\");
if(source .renameTo(new File("E:\\polo2\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
In java 1.7, new IO classes were added, including the Files utility class which has a method copy.
There is an example of usage here.
Use IOUtils Library for copy file from one location to another location.
For eg.
File source = new File("D:\\polo\\fileold");
File desc = new File("E:\\polo2\\filenew");
IOUtils.copy(source, desc);
Try this..
I use this simple code to write a few strings to the file called "example.csv", but each time I run the program, it overwrites the existing data in the file. Is there any way to append the text to it?
void setup(){
PrintWriter output = createWriter ("example.csv");
output.println("a;b;c;this;that ");
output.flush();
output.close();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
String outFilename = "out.txt";
void setup(){
// Write some text to the file
for(int i=0; i<10; i++){
appendTextToFile(outFilename, "Text " + i);
}
}
/**
* Appends text to the end of a text file located in the data directory,
* creates the file if it does not exist.
* Can be used for big files with lots of rows,
* existing lines will not be rewritten
*/
void appendTextToFile(String filename, String text){
File f = new File(dataPath(filename));
if(!f.exists()){
createFile(f);
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
out.println(text);
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
/**
* Creates a new file including all subfolders
*/
void createFile(File f){
File parentDir = f.getParentFile();
try{
parentDir.mkdirs();
f.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
}
You have to use a FileWriter (pure Java (6 or 7)) rather than PrintWriter from the Processing API.
FileWriter has a second argument in it's constructor that allows you to set a Boolean to decide whether you will append the output or overwrite it (true is to append, false is to overwrite).
The documentation is here: http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
Note you can also use a BufferedWriter, and pass it a FileWriter in the constructor if that helps at all (but I dont think it's necessary in your case).
Example:
try {
FileWriter output = new FileWriter("example.csv",true); //the true will append the new data
output.println("a;b;c;this;that ");
output.flush();
output.close();
}
catch(IOException e) {
println("It Broke :/");
e.printStackTrace();
}
As above, this will work in the PDE - and in Android - but if you need to use it in PJS, PyProcessing, etc, then you will have to hack it
dynamically read the length of the existing file and store it in an ArrayList
add a new line to the ArrayList
use the ArrayList index to control where in the file you are currently writing
If you want to suggest an enhancement to the PrintWriter API (which is probably based off of FileWriter), you can do so at Processing's Issue page on GitHub:
https://github.com/processing/processing/issues?state=open
Read in the file's data, append your new data to that, and write the appended data back to the file. Sadly, Processing has no true "append" mode for file writing.