I do have some code for serialization which does not work. I have tried to insert both CanRead() and CanWrite() in if-statements which showed they did not have permissions to read and write. I have also tried to insert 'java.io.File.setReadable' and 'java.io.File.setWriteable to true but it still throws the error.
The code is as following:
public static void save(Object obj, String filename) throws FileNotFoundException, IOException
{
File f = new File("c:/DatoChecker/" + filename);
File dir = new File("c:/DatoChecker");
if(!dir.exists())
dir.mkdirs();
f.setReadable(true);
f.setWritable(true);
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream op = null;
ObjectOutputStream objectStream = null;
op = new FileOutputStream(f);
objectStream = new ObjectOutputStream(op);
objectStream.writeObject(obj);
objectStream.close();
}
public static Object fetch(String filename) throws FileNotFoundException, IOException, ClassNotFoundException
{
File f = new File("c:/DatoChecker" + filename);
File dir = new File("c:/DatoChecker");
if(!dir.exists())
dir.mkdirs();
f.setReadable(true);
f.setWritable(true);
if(!f.exists())
{
f.createNewFile();
}
FileInputStream ip = null;
ObjectInputStream objectStream = null;
Object obj = null;
ip = new FileInputStream(f);
objectStream = new ObjectInputStream(ip);
obj = objectStream.readObject();
ip.close();
objectStream.close();
return obj;
}
Stacktrace:
SEVERE: null
java.io.IOException: access denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at com.check.me.Serialization.fetch(Seralization.java:39)
at com.check.me.GoodsList.load(GoodsList.java:82)
at com.check.me.START.main(START.java:22)
The one for save is congruet from GoodsList (just save instead of load) and up but it is quite a bit longer below so I will leave it out for now.
Thanks for the help beforehand
Highace2
You state that you did not have permission to read or write. And, indeed, you get an error telling you that you don't have permission. You need to change the ACL on the directory in which you are creating the file, or pick a different directory.
Related
I'm trying to read and write objects into a file. Reading the output into a new object works, but every value is null.
Here's the code:
public void read() throws Exception
{
try
{
FileInputStream fIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fIn);
Object obj = in.readObject();
System.out.println(obj);
public void save() throws Exception
{
FileOutputStream fOut = new FileOutputStream(file.toString());
ObjectOutputStream out = new ObjectOutputStream(fOut);
out.writeObject(this);
out.flush();
out.close();
}
Here is the file output: (image of output)
I'd like to receive the values I previously wrote to the file in the new object created, however all I get is null for all values.
Edit: since people are asking for the entire class, and I have no idea what code could be causing what, here's the entire UserFile class: https://pastebin.com/Gr1tcGsg
I have ran that code and it works which means you most likely read before you write or you got an exception such as InvalidClassException: no valid constructor which would make sense in your case.
The code I ran:
public class SavedObject implements Serializable
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
new SavedObject();
}
private final int random;
private SavedObject() throws IOException, ClassNotFoundException
{
random = ThreadLocalRandom.current().nextInt();
File file = new File("Object.txt");
save(file);
read(file);
}
private void save(File file) throws IOException
{
FileOutputStream fileOutput = new FileOutputStream(file);
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(this);
objectOutput.close();
fileOutput.close();
System.out.println(this);
}
private void read(File file) throws IOException, ClassNotFoundException
{
FileInputStream fileInput = new FileInputStream(file);
ObjectInputStream objectInput = new ObjectInputStream(fileInput);
Object obj = objectInput.readObject();
System.out.println(obj);
objectInput.close();
fileInput.close();
}
public String toString()
{
return "SavedObject(Random: " + random + ")";
}
}
Which prints:
SavedObject(Random: -2145716528)
SavedObject(Random: -2145716528)
Also a few tips for you:
Don't have a try-catch if you throws
Have more readable variable names
Send more code in your next question
ObjectOutputStream is not recommended, if you can, you should write the values as they are
Don't use throws "Exception" instead use throws "
Put the file in instead of file.toString()
I found the problem, it was that in my constructor I wasn't correctly applying the retrieved info from the file. Thanks for everyone's help.
I am new to google drive integration.
I saved an image in google drive and I got that file by below method.
File file = getDriveService().files().get(fileId).execute();
Now when I tried to convert this file into InputStream and write this InputStream in HttpResponse then the file returns but the image is not displayed.
public InputStream convertGoolgeFileToInputStream( String fileId ) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
getDriveService().files().get(fileId).executeAndDownloadTo(outputStream);
InputStream in = new ByteArrayInputStream(outputStream.toByteArray());
return in;
//return getDriveService().files().get(fileId).executeAsInputStream();
}
You may want to try checking the download example Drive sample
private static void downloadFile(boolean useDirectDownload, File uploadedFile)
throws IOException {
// create parent directory (if necessary)
java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new IOException("Unable to create parent directory");
}
OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getTitle()));
MediaHttpDownloader downloader =
new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
downloader.setDirectDownloadEnabled(useDirectDownload);
downloader.setProgressListener(new FileDownloadProgressListener());
downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out);
}
I have a Byte[] array that i want to put it's content into a temporary file .
I have tryied to do it like this
try {
tempFile = File.createTempFile("tmp", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(sCourrier.getBody());
} catch (IOException e) {
e.printStackTrace();
}
but i want that I specify the filename by myself so not generated by the jvm
You can directly give the location and file name or You can access local filesystem and find the temp directory
String tempDir=System.getProperty("java.io.tmpdir");
you can use temp directory and your custom file name.
public static void main(String[] args) {
try {
String tempDir=System.getProperty("java.io.tmpdir");
String sCourrier ="sahu";
File file = new File(tempDir+"newfile.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sCourrier.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
You can use Guava Files.createTempDir():
File file = new File(Files.createTempDir(), fileName.txt);
But because the API is deprecated and they also recommend to use Nio with more params:
Path createTempDirectory(String prefix, FileAttribute<?>... attrs)
so it would be better if you have a method yourself:
File createTempFile(String fileName, String content) throws IOException {
String dir = System.getProperty("java.io.tmpdir");
File file = new File(dir + fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(content.getBytes(StandardCharsets.UTF_8));
}
return file;
}
i'm attempting to fetch a list of files from server and copy them to directory .
and this error prompts.
java.rmi.NoSuchObjectException: no such object in table
at javafxhomeui_1.HomeUI_2Controller.writeFileToLocalHDD(HomeUI_2Controller.java:427)
at javafxhomeui_1.HomeUI_2Controller.initialize(HomeUI_2Controller.java:312)
HomeUI_2Controller.java
RemoteInputStream ris= null;
File[] iconlist=null;
try {
File appicon=new File("D:\\SERVER\\Server Content\\Apps\\icons");
iconlist=appicon.listFiles();
for (File file1 : iconlist) {
ris = downloadcontroller.getFile(file1.getAbsolutePath());
System.out.println(file1.getName());
}
} catch (Exception ex) {
Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
}
try {
for (File file1 : iconlist) {
//System.out.println("D:\\client\\Temp\\"+file1.getName());
/*line:312 */ writeFileToLocalHDD(ris,"D:\\client\\Temp\\"+file1.getName());
}
} catch (Exception ex) {
Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
}
public static void writeFileToLocalHDD(RemoteInputStream inFile, String fileLocation) throws IOException {
// wrap RemoteInputStream as InputStream (all compression issues are dealt
// with in the wrapper code)
/* line:427*/ InputStream istream = RemoteInputStreamClient.wrap(inFile);
BufferedInputStream bis = new BufferedInputStream(istream);
//downloaded file...
File file = new File(fileLocation);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
FileChannel channel = fileOutputStream.getChannel();
byte b[] = new byte[1024];
long startTime = System.currentTimeMillis();
while (bis.available()>0) {
bis.read(b);
System.out.println((System.currentTimeMillis() - startTime)/1000);
ByteBuffer buffer = ByteBuffer.wrap(b);
channel.write(buffer);
}
bis.close();
fileOutputStream.flush();
channel.close();
fileOutputStream.close();
}
////////////////////////////////////////////////
public RemoteInputStream getFile(String fileName) throws IOException {
// create a RemoteStreamServer (note the finally block which only releases
// the RMI resources if the method fails before returning.)
//read data
RemoteInputStreamServer istream = null;
try {
File file = new File(fileName);
System.out.println(file.exists());
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);
istream = new SimpleRemoteInputStream(bufferedInputStream);
// export the final stream for returning to the client
//send data
RemoteInputStream result = istream.export();
// after all the hard work, discard the local reference (we are passing
// responsibility to the client)
istream = null;
return result;
} finally {
// we will only close the stream here if the server fails before
// returning an exported stream
if (istream != null) {
istream.close();
}
}
}
////////////////////////////////////
rmi works on a stub and skeleton structure.
Exception that is thrown has something to do with rmi Registry. The Object is not found because it is not available from RMI resistry.
A NoSuchObjectException is thrown if an attempt is made to invoke a method on an object that no longer exists in the remote virtual machine
as in javaDoc of the Exception thrown
I wanted to Override a file which is used by other process in windows machine using Java Program, for which I want obtain force lock on file , please guide me how can I achieve.
I am using org.apache.commons.io.monitor.FileAlterationObserver to check whether file is changed or not if changed i want to override dest file with src file.
I tried both code snippets I am getting below exception.
Exception :
The process cannot access the file because it is being used by another process
at java.io.RandomAccessFile.open(Native Method)
Code Snippet1
FileAlterationObserver observer = new FileAlterationObserver(folderToObserve);
observer.addListener(new FileAlterationListener() {
#Override
public void onFileChange(File file) {
System.out.println("File changed , file.getAbsolutePath() : "+file.getAbsolutePath());
file.delete();
try {
FileUtils.copyFile(srcFile, file);
//checkAndUpdateFile(srcFile, file);
} catch (Exception e) {
System.out.println("Error In overriding file");
e.printStackTrace();
}
}
Code Snippet2
private static void checkAndUpdateFile(File src, File dest) throws IOException {
FileInputStream in = new FileInputStream(src);
FileChannel srcChannel = in.getChannel();
FileChannel destChannel = null;
FileLock destLock = null;
try {
if (!dest.exists()) {
final RandomAccessFile destFile = new RandomAccessFile(dest, "rw");
destChannel = destFile.getChannel();
destLock = destChannel.lock();
copyFileChannels(srcChannel, destChannel);
dest.setLastModified(src.lastModified());
} else {
final RandomAccessFile destFile = new RandomAccessFile(dest, "rw");
destChannel = destFile.getChannel();
destLock = destChannel.lock();
if (!compareFileChannels(srcChannel, destChannel)) {
copyFileChannels(srcChannel, destChannel);
dest.setLastModified(src.lastModified());
}
}
}