I have a third-party library that requires the populating of a java File object at runtime. I have extended this code, but I do not need the file-related part. However, for my purposes, I am forced to create and use the File object and read from it.
Is there a way I can have the binary equivalent of an already-read file available at runtime? Or is there a way to have a file as byte-code already available for a File object? Please assume with my situation that going to a file-system to retrieve and open a file is not an option.
Thanks for any insights!
You can create a temp file and delete after your program finishes.
import java.io.*;
import java.nio.file.*;
public class Program {
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
String tmpDir = System.getProperty("java.io.tmpdir");
Path filePath = Paths.get(tmpDir, filename);
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}
If you need a PHYSICAL file on they system, you can create it like so:
import java.io.*;
import java.nio.file.*;
public class Program {
public static final String TMP_DIR = System.getProperty("java.io.tmpdir");
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
Path filePath = null;
try {
byte[] data = { 0 }; // Write a single byte of data
filePath = Files.write(Paths.get(TMP_DIR, filename), data);
} catch (IOException e) {
e.printStackTrace();
}
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}
Related
I am not sure why file , BankAccount.ser is empty after successful run of below code. BankAccount.ser file is a class path resource. After successful run of SuccessfulSerializationTestDriver , BankAccount.ser is zero bytes on disk and has no contents.
public class SuccessfulSerializationTestDriver {
public static void main(String[] args) {
long accountNumber=12033456;
String bankName="SBI";
String branch="NOIDA";
SerializableBankAccount sBankAccount = new SerializableBankAccount();
sBankAccount.setAccountNumber(accountNumber);
sBankAccount.setBankName(bankName);
sBankAccount.setBranch(branch);
try(FileOutputStream fileOut =new FileOutputStream("BankAccount.ser")){
ObjectOutputStream out= new ObjectOutputStream(fileOut);
out.writeObject(sBankAccount);
out.flush();
out.close();
System.out.println("Bank Account is successfully serialized");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Serializable class is ,
public class SerializableBankAccount implements Serializable {
private static final long serialVersionUID = 1L;
private long accountNumber;
private String bankName;
private String branch;
public long getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(long accountNumber) {
this.accountNumber = accountNumber;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
#Override
public String toString(){
return accountNumber+","+bankName+","+branch;
}
}
EDIT : I wrote deserializer and I am getting object successfully - so it just seems a visibility issue. Somehow file is shown of zero bytes.
public class SuccessfulDeSerializationTestDriver {
public static void main(String[] args) {
SerializableBankAccount sBankAccount = null;
try(FileInputStream fileIn =new FileInputStream("BankAccount.ser")){
ObjectInputStream inStream= new ObjectInputStream(fileIn);
sBankAccount= (SerializableBankAccount) inStream.readObject();
inStream.close();
System.out.println("Successfully Deserialized Object is "+sBankAccount);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Successfully Deserialized Object is 12033456,SBI,NOIDA
If the file you're looking at is zero bytes, but it deserializes successfully, it sounds like the file is being created elsewhere. Perhaps specify the path explicitly when you create the file name for a start. The file with size 0, may be from an older run - delete that on disk, and see if it gets created again.
I am not able to recreate the problem you're having. When I run your code the BankAccount.ser file is created and is not empty. In fact I wrote a deserialization test to see if I could get the object back by reading the file and it works fine.
Here is the deserializing class in case you want it:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeserializationTestDriver {
public static void main(String[] args) {
try(FileInputStream fileInput =new FileInputStream("BankAccount.ser")){
ObjectInputStream input = new ObjectInputStream(fileInput);
SerializableBankAccount sBankAccount = (SerializableBankAccount) input.readObject();
input.close();
System.out.println("Bank Account is successfully deserialized: "+sBankAccount.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I also added a toString method to your SerializableBankAccount:
#Override
public String toString() {
return "SerializableBankAccount [accountNumber=" + accountNumber
+ ", bankName=" + bankName + ", branch=" + branch + "]";
}
After running your serialization code and then running the above deserialization I get this output:
Bank Account is successfully deserialized: SerializableBankAccount [accountNumber=12033456, bankName=SBI, branch=NOIDA]
So clearly the code is fine, which means it has to be something to do with the environment. I suggest checking whether you're running the program with correct privileges, permissions, etc. It seems that something external to your code is preventing you from writing to the file. Either that or perhaps you're looking at the wrong file, verify you have the correct path and check the file creation and modification dates.
I've found answers to various questions on here before, but this is my first time asking one. I'm kicking around an idea for my final project in my computer programming class, and I'm working on a few proof of concept programs in Java, working in Eclipse. I don't need anything more than to get the filepaths of the contents of a directory and write them to a .txt file. Thanks in advance!
Edit: I am posting my code below. I found a snippet of code to use for getting the contents and print them to the screen, but the print command is a placeholder that I'll replace with a write to folder command when I can.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ScanFolder {
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
}
EDIT: I've enclosed the OutputStreamWriter in a BufferedWriter
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("txt.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
writeContentsOfFileToAFile(new File("."), out, true); // change true to
// false if you
// don't want to
// recursively
// list the
// files
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void writeContentsOfFileToAFile(File parent, BufferedWriter out, boolean enterIntoDirectory) {
for (File file : parent.listFiles()) {
try {
out.write(file.toString() + "\r\n");
} catch (IOException e) {
e.printStackTrace();
}
if (enterIntoDirectory && file.isDirectory())
writeContentsOfFileToAFile(file, out, enterIntoDirectory);
}
}
Is this what you need?
the following code is incomplete but the main focus of my question is on the method processConfig() anyway. It reads the properties out of a file and I want to handover these properties to the method replaceID(). It worked already when the content of processConfig was in the main()-method. But now I wanted to put this code into it´s own method. What is the best way of handing over the properties (which I saved in Strings like difFilePath). I´m not that familiar with OO-programming and want to understand the concept. Thanks for your help.
public class IDUpdater {
....
public static void main(String[] args) throws Exception {
//Here I want to call the variables from processConfig() to make them available for replaceID(...)
replaceID(difFilePath, outputDifPath, encoding);
}
public static void replaceID(String difFilePath, String outputDifPath, String encoding) throws Exception{
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
String difFilePath = prop.getProperty("dif_file_path");
String outputDifPath = prop.getProperty("output_dif_path");
String encoding = prop.getProperty("encoding");
}
}
You've to declare your variables globally. This way they can be accessed in each method. After you've declared them globally you first call your processConfig in your main method, which will set your variables to what they should be.
public class IDUpdater {
private String difFilePath;
private String outputDifPath;
private String encoding;
public void main(String[] args) throws Exception {
processConfig();
replaceID();
}
public void replaceID() throws Exception{
// You can use your variables here.
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
difFilePath = prop.getProperty("dif_file_path");
outputDifPath = prop.getProperty("output_dif_path");
encoding = prop.getProperty("encoding");
}
}
Note that I declared the variables privately. For more information about protecting your variables see https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx.
You may want to read an article (or even better yet - a book) on topic of encapsulation and objects. This or this may be a good starting point for you. There is no point in anyone fixing your code, if you don't understand the concepts behind it.
I have written a java code to create a file if file name is provided in command line argument, if command line argument is not entered it will create file in default folder
import java.io.File;
import java.io.IOException;
public class Outputlogs {
private final String path = "C:/temp/logs.txt";
public void createLogFile(String fileName)
{
if(fileName != null && !fileName.isEmpty())
{
File yourFile = new File(fileName);
if(!yourFile.exists()) {
try {
yourFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
File yourFile = new File(path);
if(!yourFile.exists()) {
try {
yourFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MainClass()
{
public static void main(String[] argv)
{
String fileName = argv[0];
Outputlogs logs= new Outputlogs();
logs.createLogFile(fileName);
}
If i am providing command line arguments, its successfully creating the file but if command line argument is not entered, i am getting java.lang.ArrayIndexOutOfBoundsException
How to achieve my scenario if command line argument is not entered it should create default folder. Please help
Something like this:
public static void main(String[] args) {
if (args.length > 0)
createLogFile(args[0]) ;
}
I'm assuming that at some point, you are setting filename = args[0], otherwise you wouldn't be getting an array access error. If no argument is provided, the array args will be null, so accessing args[0] will return an ArrayIndexOutofBounds exception. Just check the length first:
if(args.length > 0)
fileName = args[0];
else
fileName = path;
Then you can combine your if/else statement into a single statement since at this point it filename will be either the argument or your default path:
File yourFile = new File(fileName);
if(!yourFile.exists()) {
try {
yourFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code works.
import java.io.File;
import java.io.IOException;
public class Test {
private static final String path = "C:/temp/logs.txt";
public static void main(String[] args) {
if(args.length > 0) {
createLogFile(args[0]);
} else {
createLogFile(path);
}
}
public static void createLogFile(String fileName)
{
File f = new File(fileName);
if(!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
argv[0] means the first element in the argument-list (Array), so you have to check if there is at least one argument provided.
You can check the amount of items in the array with array.length, so everything above 0 will tell you that you can access the first (or second,third) argument.
public static void main(String[] argv)
{
String fileName = (argv.length > 0) ? argv[0]:path; // changed
Outputlogs logs= new Outputlogs();
logs.createLogFile(fileName);
}
This line will check if the length of the array is above 0 set the fileName to argv[0] if it is or take the path variable if it isn't.
I use eclipse and put a File called "example.txt" into the bin-folder where the class files are generated (and into the sub-folder of the package). But still, the program allways prints out the error message i wrote for the case the file is not found.
Main Class:
import java.io.BufferedReader;
public class Main {
public static void main(String[] args){
BufferedReader file = Console.file("example.txt");
...
}
Console Class:
public final class Console {
public static BufferedReader file(String args) {
BufferedReader file = null;
try {
file = new BufferedReader(new FileReader(args));
} catch (FileNotFoundException e) {
println("Error, file not found!");
System.exit(1);
}
return file;
}
}
any ideas?
For the Eclipse project, the current path is the project folder, not the BIN directory, you can use the code below to get the current path so that you will know where to put and how to access the file.
import java.io.File;
import java.io.IOException;
public class MainTest {
public static void main(String[] args)
{
File directory = new File("");
try {
System.out.println(directory.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So in your case, the path you specify should be: ./bin/example.txt