I'm using Netbeans 7.2 on OS X 10.9. The JFileChooser.showSaveDialog() fails on certain occasions. Before I call the showSaveDialog, I call showOpenDialog to open an .srt file. The show dialog fails only when I open certain files esp. from /Volumes/.. on a mounted device. Here's the code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.io.FilenameUtils;
public class FileSaver extends JFileChooser {
private int result;
private File subFile;
private File save;
private File filename;
private String rectifiedSub;
private FileNameExtensionFilter filter;
public FileSaver(File subFile, String rectifiedSub) {
this.subFile = subFile;
this.rectifiedSub = rectifiedSub;
filename = new File(System.getProperty("user.home"));
filter = new FileNameExtensionFilter("Subtitle Files (*.srt)", "srt");
}
public void createAndShowGUI() {
System.out.println("6");
this.setDialogTitle("Select destination");
System.out.println("6");
this.setCurrentDirectory(filename);
System.out.println("6");
this.setSelectedFile(new File(subFile.getName()));
System.out.println("6");
this.setFileFilter(filter);
System.out.println("6");
result = this.showSaveDialog(this);
System.out.println("6");
if(result == JFileChooser.APPROVE_OPTION) {
save = fixExtension(this.getSelectedFile());
write(save);
}
this.setVisible(true);
}
public void write(File save) {
FileWriter fw = null;
try {
fw = new FileWriter(save);
fw.write(rectifiedSub);
} catch (IOException ex) {
Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fw.close();
} catch (IOException ex) {
Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public File fixExtension(File file) {
if(!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase(".srt"))
file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName()).concat(".srt"));
return file;
}
}
Output:
6
6
6
6
6
It stops at the 6 before the line result = this.shhowSaveDialog(this);. The program freezes after that and the save dialog doesn't show up. It works perfectly fine on some files. Somebody tell me whats happening ?
Git: https://github.com/Jimmy-666/Subzero.git
Related
I need to create a utility, which downloads the files from the box folder. But I am unable to get it working though:
package com.box.sdk.example;
import com.box.sdk.BoxConfig;
import com.box.sdk.BoxDeveloperEditionAPIConnection;
import com.box.sdk.BoxFile;
import com.box.sdk.BoxFolder;
import com.box.sdk.BoxItem;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PlayGround {
public static void main(String[] args) {
Path configPath = Paths.get("config.json");
Path currentDir = Paths.get("").toAbsolutePath();
try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) {
BoxConfig boxConfig = BoxConfig.readFrom(reader);
BoxDeveloperEditionAPIConnection client = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig);
String folderId = "125601757844";
BoxFolder folder = new BoxFolder(client, folderId);
String folderName = folder.getInfo().getName();
Path localFolderPath = currentDir.resolve(Paths.get(folderName));
if (!Files.exists(localFolderPath)) {
localFolderPath = Files.createDirectory(localFolderPath);
} else {
localFolderPath = resetLocalFolder(localFolderPath);
}
for (BoxItem.Info itemInfo : folder) {
if (itemInfo instanceof BoxFile.Info) {
BoxFile.Info fileInfo = (BoxFile.Info) itemInfo;
BoxFile file = new BoxFile(client, fileInfo.getID());
String localFilePath = localFolderPath.resolve(Paths.get(fileInfo.getName())).toAbsolutePath()
.toString();
FileOutputStream stream = new FileOutputStream(localFilePath);
file.download(stream);
stream.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static Path resetLocalFolder(Path localFolderPath) throws IOException {
Files.list(localFolderPath).forEach(file -> {
System.out.println(file.getFileName());
try {
Files.delete(file.toAbsolutePath());
} catch (IOException e) {
}
});
Files.delete(localFolderPath);
localFolderPath = Files.createDirectory(localFolderPath);
return localFolderPath;
}
}
When I run this code, I get the following exception:
Exception in thread "main" com.box.sdk.BoxAPIResponseException: The API returned an error code [404 | lsgp4zgkfg6qipxg.0d094ed7daa5f78921603840e0fa470e1] not_found - Not Found
at com.box.sdk.BoxAPIResponse.<init>(BoxAPIResponse.java:92)
at com.box.sdk.BoxJSONResponse.<init>(BoxJSONResponse.java:32)
at com.box.sdk.BoxAPIRequest.trySend(BoxAPIRequest.java:680)
at com.box.sdk.BoxAPIRequest.send(BoxAPIRequest.java:382)
at com.box.sdk.BoxAPIRequest.send(BoxAPIRequest.java:349)
at com.box.sdk.BoxFolder.getInfo(BoxFolder.java:289)
at com.box.sdk.example.PlayGround.main(PlayGround.java:26)
Note: I am able to run the above code, by using developer token, which lasts for 1 hour, but I can't build my production application on such volatile code.
BoxAPIConnection client = new BoxAPIConnection("3i8b5sPnxUotd5etDuUkzGjXXzBphty9");
I'm using tTorrent Java implementation of the BitTorrent protocol. I'm at the point where I have to deal with a Tracker. The example code from the official repository loads torrent files from a given directory and announce them to the tracker. Then, starts it. I was hoping that the tracker would look for new torrent files in the directory automatically but, it doesn't seem to do so.
I pulled in a DirectoryWatcher and listened to create event; filtering torrent files. Passing the reference of Tracker object, I can announce the new file but, it doesn't seem to do anything.
How can I make the tracker aware of possible new torrent files in the directory while it's running?
DirectoryAwareTracker.java
import com.turn.ttorrent.tracker.TrackedTorrent;
import com.turn.ttorrent.tracker.Tracker;
import io.methvin.watcher.DirectoryChangeEvent;
import io.methvin.watcher.DirectoryChangeListener;
import io.methvin.watcher.DirectoryWatcher;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Path;
public class DirectoryAwareTracker extends Tracker {
private DirectoryWatcher watcher;
private static final FilenameFilter torrentFilenameFilter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".torrent");
}
};
DirectoryAwareTracker(InetSocketAddress address, Path directoryToWatch) throws IOException {
super(address);
File parent = new File(".");
for (File f : parent.listFiles(torrentFilenameFilter)) {
System.out.println("Loading torrent from " + f.getName());
try {
announce(TrackedTorrent.load(f));
} catch (Exception e) {
}
}
System.out.println("Starting tracker with {} announced torrents..." + getTrackedTorrents().size());
start();
watcher = DirectoryWatcher.create(directoryToWatch, new DirectoryChangeListener() {
#Override
public void onEvent(DirectoryChangeEvent directoryChangeEvent) throws IOException {
switch (directoryChangeEvent.eventType()) {
case CREATE:
File newFile = new File(directoryChangeEvent.path().toString());
System.out.println(directoryChangeEvent.path().toString());
System.out.println(newFile.isFile());
System.out.println(newFile.getName().endsWith(".torrent"));
if (newFile.isFile() && newFile.getName().endsWith(".torrent")) {
try {
announce(TrackedTorrent.load(newFile));
} catch (Exception e) {
}
}
break;
}
}
});
}
public void stopWatching() {
try {
watcher.close();
}
catch(Exception e) { }
}
public void watch() {
watcher.watch();
}
}
Was trying to get a JFrame added to see if it would help with using launch4j to convert a small jar file to an .exe. I wrote a short program to help sort HPLC data at work and want to make it just a simple point and click.
It works when I run it from the command line java KFile and the JFileChooser lets me choose directories for the script to work on. When I converted it to the .exe, the JFileChooser never rendered and the .exe closes.
I read that I might need a JFrame parent and so I created a JFrame, but now the script hangs before completion as if waiting for the frame to close. I'm pretty new to java, so I'm not sure how I to resolve this issue.
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.FileVisitResult;
import java.nio.MappedByteBuffer;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import java.util.Collection;
import java.util.ArrayList;
import java.nio.file.SimpleFileVisitor;
public class KFile extends SimpleFileVisitor<Path> {
public static void main(String[] args) {
Path currPath = Paths.get("");
String currDir = currPath.toAbsolutePath().toString();
System.out.println(currDir);
File dataDir = chooseDir("open");
File destDir = chooseDir("save");
if(!destDir.exists()) {
try {
destDir.mkdir();
}
catch (SecurityException se) {
System.out.println("Couldn't make directory!");
}
}
int n = 0;
if(dataDir.exists()) {
Collection<Path> allDir = new ArrayList<Path>();
try {
addTree(dataDir.toPath(),allDir);
}
catch (IOException e) {
System.out.println("Error with scanning");
}
for( Path thisPath : allDir ) {
if(thisPath.toString().contains("Report.pdf")) {
Path thisDir = thisPath.getParent();
File f = new File(thisDir.toString(), "\\Report.txt");
n = n + 1;
String fileName = "Report " + n + ".pdf";
try {
fileName = parseName(f);
System.out.println(fileName);
} catch (IOException e) {
e.printStackTrace();
}
File thisFile = new File(destDir + "\\" + fileName);
try {
copyFile(thisPath.toFile(),thisFile);
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
}
public static boolean copyFile(File sourceFile, File destFile) throws IOException {
//create file if it doesn't exist.
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
return true;
}
return false;
}
}
public static File chooseDir(String s) {
JFrame myFrame = new JFrame("HPLC Data Transfer");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
JFileChooser chooser = new JFileChooser();
File currDir = new File(System.getProperty("user.home") + "\\Documents");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(currDir);
int choice = 0;
if (s.equals("save")) {
choice = chooser.showSaveDialog(myFrame);
} else {
choice = chooser.showOpenDialog(myFrame);
}
myFrame.setVisible(false);
myFrame.removeAll();
if(choice == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open: " + chooser.getSelectedFile().getName());
return chooser.getSelectedFile();
}
return new File("");
}
static String parseName(File f) throws IOException {
BufferedReader textReader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
int lnCnt = 32;
String[] fileData = new String[lnCnt];
for (int i = 0; i < lnCnt; i++) {
fileData[i] = textReader.readLine();
}
fileData[1] = fileData[1].replace("\uFEFF","");
String name = fileData[1].substring(13) + ".pdf";
textReader.close();
return name;
}
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
}
You could try changing
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
and then call
myFrame.dispose();
to terminate the JFrame.
Since javadocs says EXIT_ON_CLOSE terminates the whole program using System.exit(); I'm not sure if that's the problem that is stopping your application but I hope it helps :)
It looks like you just called setVisible(false) when dealing with your JFrame. That just hides your JFrame, it doesn't get rid of it. If you want to get rid of your frame entirely (and all of its resources), call myFrame.dispose();
I am trying to append text to a text file on the Google Drive. But when I write, it whole file is overwritten. Why can't I just add the text in the end of the file?
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, id);
file.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
msg.Log("ContentsOpenedCallBack");
if (!driveContentsResult.getStatus().isSuccess()) {
Log.i("Tag", "On Connected Error");
return;
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
try {
msg.Log("onWrite");
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.append(et.getText().toString());
writer.close();
driveContents.commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Finally I've found the answer to append the text on the drive document.
DriveContents contents = driveContentsResult.getDriveContents();
try {
String input = et.getText().toString();
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("\n"+input);
writer.close();
driveContentsResult.getDriveContents().commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
SO
The reason is that commit's default resolution strategy is to overwrite existing files. Check the API docs and see if there is a way to append changes.
For anyone facing this problem in 2017 :
Google has some methods to append data Here's a link!
Though copying the method from google didn't worked entirely for me , so here is the class which would append data : ( Please note this is a modified version of this code link )
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = result.getDriveId();
DriveFile file = driveId.asDriveFile();
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
System.out.println("0"+sp.getString("drive_id","1"));
DriveContentsResult driveContentsResult=file.open(getGoogleApiClient(), DriveFile.MODE_READ_WRITE, null).await();
System.out.println("1");
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
try {
System.out.println("2");
ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
System.out.println("3");
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
writer.close();
System.out.println("4");
driveContents.commit(getGoogleApiClient(), null).await();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
};
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
Existing_File_id is the resource id. Here is one link if you need resource id a link
I'm using an IntentService to append single NMEA strings to a log file stored in the external public storage on an Android device, but I'm getting inconsistent behavior.
First off the log file does not appear when the device is connected for USB debugging. I read that many Android devices cannot write to external storage when connected via USB, but even when it is run disconnected from USB, it may take several times of turning it on and off and rerunning the applications before the log file appears in the file system. If I do not clear the log, I still have to restart the phone before it will begin appending to the file again.
How can I get the file to appear consistently everytime?
import android.app.IntentService;
import android.content.Intent;
public class LogFileService extends IntentService {
DebugLog debug = new DebugLog("LogFileService");
public static final String GPS_STR = "GPS_STR";
public static final String FILE_PATH = "FILE_PATH";
public static final String FILE_NAME = "gps_data.txt";
public LogFileService() {
super("LogFileService");
}
#Override
protected void onHandleIntent(Intent intent) {
debug.log("Handling intent");
String data = intent.getStringExtra(GPS_STR);
debug.log("Writing " + data);
GpsLogFile logFile = new GpsLogFile(FILE_NAME);
logFile.open();
logFile.write(data);
logFile.close();
}
#Override
public void onCreate() {
super.onCreate();
debug.log("Created");
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import android.content.Context;
import android.os.Environment;
public class GpsLogFile {
DebugLog debug = new DebugLog("LogFile");
private File filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
);
private File logFile = null;
private String fileName = null;
private PrintWriter fileOut = null;
public GpsLogFile(String name) {
fileName = name;
}
public void open() {
try {
filePath.mkdirs();
if (!isExternalMediaAvailable()) {
throw new IOException("External media not available.");
}
logFile = new File(filePath, fileName);
//logFile.mkdirs();
if (!logFile.exists()) {
logFile.createNewFile();
}
fileOut = new PrintWriter(
new FileOutputStream(logFile.getAbsolutePath(), true)
);
} catch (IOException e) {
debug.log("Unable to open file.");
debug.log(e.getMessage());
}
}
public void write(String data) {
debug.log("Writing to " + logFile.getAbsolutePath() + " " + data);
try {
fileOut.write(data);
//fileOut.newLine();
checkPrintWriterError(fileOut);
fileOut.flush();
} catch (IOException e) {
debug.log("Unable to write");
debug.log(e.getMessage());
}
}
public void close() {
if (null != fileOut) {
try {
fileOut.close();
checkPrintWriterError(fileOut);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void checkPrintWriterError(PrintWriter writer) throws IOException {
if (true == writer.checkError()) {
throw new IOException("Print writer error.");
}
}
}