I want to get data from the clipboard and store it in a .txt file.
How do I create the .txt file? I have read a lot about getting data from a file but not the other way around.
Here is my code:
public void CallClipboard (){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard();
System.out.println(grabbed);
}
public String ReadClipboard () {
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
I have solved it with the current code thanx for the tips
public static void CallClipboard (String file){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard(file);
System.out.println(grabbed);
}
public static String ReadClipboard (String file) {
File testFile = new File(file);
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
try {
setContents(testFile, returnText);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
//use buffering
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
//FileWriter always assumes default encoding is OK!
output.write( aContents );
}
finally {
output.close();
}
}
Take a look at FileWriter and BufferedWriter for writing Strings to files.
Related
So I am new in programing and i adding a feature in my app which save all sharedpreference key in value in Device internal data folder by using fileoutputStream like this add all data in map and store in jsonobject
private String maptojson(){
Map<String, ?> map = prf.getAll();
JSONObject object = new JSONObject();
for (Map.Entry<String,?> entry : map.entrySet()){
try {
object.put( entry.getKey(), entry.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return object.toString();
}
Now Use FileOutputStream for write file in internal Storage "data'
public void backupSetting() {
Throwable th;
FileOutputStream fileOutputStream;
IOException e;
FileOutputStream fileOutputStream2 = null;
File externalStorageDirectory = Environment.getExternalStorageDirectory();
if (externalStorageDirectory.exists() && externalStorageDirectory.canWrite()) {
if (externalStorageDirectory.getUsableSpace() >= 1048576) {
File file = new File(externalStorageDirectory.toString() + "/data/MyApp/" + "MyAppSetting.ma");
try {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(maptojson().getBytes());
fileOutputStream.flush();
fileOutputStream.close();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} catch (IOException e3) {
e = e3;
try {
e.printStackTrace();
if (fileOutputStream != null) {
}
} catch (Throwable th2) {
th = th2;
fileOutputStream2 = fileOutputStream;
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e4) {
e4.printStackTrace();
throw th;
}
}
throw th;
}
}
} catch (IOException e5) {
e = e5;
fileOutputStream = null;
e.printStackTrace();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
e6.printStackTrace();
}
}
} catch (Throwable th3) {
th = th3;
if (fileOutputStream2 != null) {
}
try {
throw th;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Now i want to add restore setting means restore setting by using that file "MyAppSetting.ma". I know i can do it by using FileInputStream but I don't understand how to do? please help if you could
Hello all I am having a problem when exporting a named file to the device internal storage for my apps Sqlite database name.
I am getting the error
java.io.FileNotFoundException: /storage/emulated/0/Download/:/09/12/2017-JDO.db: open failed: ENOENT (No such file or directory)
when trying to name the file /09/12/2017-JDO.
I am using File.pathSeparator() with the passed in file name but still am not having any luck. I think it has to do with the / in the file name which is the reason why I tried the File.pathSeparator() to begin with since I want that option for naming the file if the user wants to include the date in that format or in combination with the /.
Here are some code snippets of the methods I am using to try and accomplish this and to show what I am trying to do.
/*
This method saves and exports the current database to the device's internal Downloads folder
This is the default named database
*/
public void backUpDatabase() {
/* Open your local db as the input stream */
DBHelper anotherDbHelper = null;
try {
try {
anotherDbHelper = new DBHelper(ExistingTallyActivity.this);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String path = null;
if (anotherDbHelper != null) {
path = String.valueOf(getApplicationContext().getDatabasePath(anotherDbHelper.getDatabaseName()));
}
File dbFile = null;
if (path != null) {
dbFile = new File(path);
}
FileInputStream fis = null;
try {
if (dbFile != null) {
fis = new FileInputStream(dbFile);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String outFileName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/Pipe_Tally");
/* Open the empty db as the output stream */
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(outFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* Transfer bytes from the input-file to the output-file */
byte[] buffer = new byte[1024];
int length;
try {
if (fis != null) {
while ((length = fis.read(buffer)) > 0) {
try {
if (outputStream != null) {
outputStream.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
/* Close the streams */
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (anotherDbHelper != null) {
anotherDbHelper.close();
}
}
/*
This method renames the database to what the user inputs they want. Note: The original db is
still present and stored in the Downloads folder as well.
*/
public void renameDbFile(String desiredDbName) {
/* Open your local db as the input stream */
DBHelper dbHelperToRename = null;
try {
try {
dbHelperToRename = new DBHelper(ExistingTallyActivity.this);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String pathRenamed = null;
if (dbHelperToRename != null) {
pathRenamed = String.valueOf(getApplicationContext().getDatabasePath(dbHelperToRename.getDatabaseName()));
}
File dbFileRenamed = null;
if (pathRenamed != null) {
dbFileRenamed = new File(pathRenamed);
}
FileInputStream fisRenamed = null;
try {
if (dbFileRenamed != null) {
fisRenamed = new FileInputStream(dbFileRenamed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* Here is where the db is renamed by the user by inserting the passed in string to the method */
String outFileNameRenamed =
(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath() + "/"+desiredDbName+".db");
// Open the empty db as the output stream
OutputStream outputStreamRenamed = null;
try {
outputStreamRenamed = new FileOutputStream(outFileNameRenamed);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* Transfer bytes from the input-file to the output-file */
byte[] bufferRenamed = new byte[1024];
int length;
try {
if (fisRenamed != null) {
while ((length = fisRenamed.read(bufferRenamed)) > 0) {
try {
if (outputStreamRenamed != null) {
outputStreamRenamed.write(bufferRenamed, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
/* Close the streams */
try {
if (outputStreamRenamed != null) {
outputStreamRenamed.flush();
outputStreamRenamed.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fisRenamed != null) {
fisRenamed.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (dbHelperToRename != null) {
dbHelperToRename.close();
}
}
/*
This method exports the database into CSV format as well by naming it the passed in string value
for the desired name.
*/
#TargetApi(Build.VERSION_CODES.KITKAT)
public void saveDbAsCsv(String desiredCsvName) {
/* Getting a instance of the DbHelper class right here. */
DBHelper dbhelperCsv = null;
try {
dbhelperCsv = new DBHelper(ExistingTallyActivity.this);
} catch (ClassNotFoundException | NoSuchFieldException e) {
e.printStackTrace();
}
/* Original name of the file dir where the db will be stored in csv format. (Just like SQLite) */
String pathRenamedCsv = null;
if (dbhelperCsv != null) {
pathRenamedCsv = String.valueOf(getApplicationContext().getDatabasePath(dbhelperCsv.getDatabaseName()));
}
/* Creating a File type here with the passed in name from above from the string */
File dbFile = getDatabasePath(pathRenamedCsv);
/*
Appending the desired name to the Downloads Directory here, which is where the new file
will be written
*/
String renamedCsvName = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/"+desiredCsvName);
File exportDir = new File(String.valueOf(renamedCsvName));
if (!exportDir.exists())
{
exportDir.mkdirs();
}
/*
Critical .csv extension here. Took me a while originally to figure out where to pass this
in at. Was at first passing it into the renamedCsvName up above and it was just returning
a folder with the .csv extension and not the file contained withn.
*/
File file = new File(exportDir, desiredCsvName+".csv");
try
{
/* Passing in the string value of the file to an instance of the CsvWriter class */
CsvWriter csvWriter = new CsvWriter(String.valueOf(file));
SQLiteDatabase db = null;
if (dbhelperCsv != null) {
db = dbhelperCsv.getReadableDatabase();
}
/* Getting a cursor from the database table Tally_File */
Cursor curCSV = null;
if (db != null) {
curCSV = db.rawQuery("SELECT * FROM Tally_File",null);
}
if (curCSV != null) {
csvWriter.writeRecord(curCSV.getColumnNames());
}
if (curCSV != null) {
while(curCSV.moveToNext())
{
/* Exporting all the columns here to write out to the csv file */
String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2),
curCSV.getString(3), curCSV.getString(4), curCSV.getString(5),
curCSV.getString(6), curCSV.getString(7), curCSV.getString(8),
curCSV.getString(9), curCSV.getString(10), curCSV.getString(11),
curCSV.getString(12), curCSV.getString(13), curCSV.getString(14), curCSV.getString(15),
curCSV.getString(16)};
/*
Critical here as I was not at first calling the writeRecord that accepted the
String[] array and was calling the toString() method on it and only getting a large
array.
*/
csvWriter.writeRecord(arrStr);
}
}
csvWriter.close();
if (curCSV != null) {
curCSV.close();
}
}
catch(Exception sqlEx)
{
Toast.makeText(this, "Error naming file", Toast.LENGTH_LONG).show();
}
}
Here is where I am calling the methods and passing in the desiredName for naming the file/Db, which is switch case dependent on a menu selection, all within the same activity.
case R.id.menu_save_and_export:
Thread threadMenuSaveAndExport = new Thread();
/*
This method verifies user permissions then calls the backUpDatabase() method to
backup the original db file before the user renames it, if desired.
*/
verifyStoragePermissions(new Runnable() {
#Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
/* Calling this method here to backup the current database*/
backUpDatabase();
}
});
/* Loading the view of activity_database_name with this LayoutInflater*/
View view = LayoutInflater.from(ExistingTallyActivity.this)
.inflate(R.layout.activity_database_name,null);
/*This editText handles the input from the user for their chosen db name*/
mEtCustomDbName = (EditText) view.findViewById(R.id.etCustomDbName);
AlertDialog.Builder alert = new AlertDialog.Builder(ExistingTallyActivity.this);
/* Taken from the strings.xml file. Says Name Database Prior To Export */
alert.setMessage(getResources().getString(R.string.name_your_db));
alert.setView(view);
/* Using the global "Ok" string from strings.xml */
alert.setPositiveButton(getResources().getString(R.string.global_ok_text), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* Passing in the results of the editText to a string here*/
String userDefinedDbName = mEtCustomDbName.getText().toString().trim();
/*
Calling this method to rename the existing db to what the user input
Note: The original db remains in the same folder, as it was previously
backed up from the backUpDatabase() method above. Using the if statement
below to check for a empty string and if it is, the file is not renamed.
Both situations display custom toast message dependent on which executes.
Also implementing the File.separator method to help with File naming
issues on the Android "Unix-like" filesystem
*/
if (userDefinedDbName.length() > 0) {
/* Naming to a .db extension with this method. Works with SQLite */
renameDbFile(File.pathSeparator+userDefinedDbName);
/* Naming to a .csv extension with this method for working with Excel */
saveDbAsCsv(File.pathSeparator+userDefinedDbName);
Toast.makeText(ExistingTallyActivity.this,
/* Using the "Database Saved" string from strings.xml */
getResources().getString(R.string.database_saved),
Toast.LENGTH_LONG).show();
}else {
Toast.makeText(ExistingTallyActivity.this,
/* Using the "Database Not Saved" string from strings.xml */
getResources().getString(R.string.database_not_saved),
Toast.LENGTH_LONG).show();
}
}
});
/* Using the global "Cancel" string from strings.xml */
alert.setNegativeButton(getResources().getString(R.string.global_cancel_text), null);
alert.setCancelable(false);
AlertDialog showAlert = alert.create();
showAlert.show();
threadMenuSaveAndExport.start();
break;
Any advice or help would be greatly appreciated with this as I do want to be able to use the naming with / if desired as an option. Thanks
I found error when filename contain with "#".
Error: java.lang.IllegalStateException: File does not exist.
But when filename without "#" still working.
String resource = "file:c:/Test#.txt";
PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
Resource[] resolveResources;
try {
resolveResources = pathResolver.getResources(resources);
if(resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resources);
}else{
for (Resource resource : resolveResources) {
if(!resource.exists()){ //true
throw new IllegalStateException("File does not exist: " + resource);
}
}
}
} catch (IOException e) {
throw new IllegalStateException("File does not exist: " + resources);
}
file names validity depends on operating system (the file system to be more accurate), so to make sure that the file can be read on any Operating system; use alphanumeric and the underscoreCharacters to avoid
in your program the problem is in the URI making function
public static void main(String[] args ){
File f = new File("ahh#.txt");
try {
if(f.createNewFile()){
System.out.println("ok"+ f.getAbsolutePath());
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// file with string path
FileInputStream fis0;
try {
fis0 = new FileInputStream(
new File(f.getAbsolutePath()));
} catch (FileNotFoundException ex) {
System.out.println("file not found with string");
}
try {
try {
// file with URI
FileInputStream fis1 =
new FileInputStream(
new File(
new URI(f.getAbsolutePath())));
} catch (URISyntaxException ex) {
System.out.println("URI???");
}
} catch (FileNotFoundException ex) {
System.out.println("file not found with URI");
}
}
It's a bit of a hack but I think you need something like this :
#Test
public void test1() {
try {
String resource = "file:c:\\tmp\\Test\u0023.txt";
PathMatchingResourcePatternResolver pathResolver = new TestPathMatchingResourcePatternResolver();
Resource[] resolveResources;
resolveResources = pathResolver.getResources(resource);
if (resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resource);
} else {
for (Resource resource2 : resolveResources) {
if (!resource2.exists()) { // true
throw new IllegalStateException("File does not exist: " + resource2);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Then you need to add modify the PathMatchingResourcePatternResolver
public class TestPathMatchingResourcePatternResolver extends PathMatchingResourcePatternResolver {
public TestPathMatchingResourcePatternResolver() {
super(new TestDefaultResourceLoader());
}
}
Then you need to modify the DefaultResourceLoader
public class TestDefaultResourceLoader extends DefaultResourceLoader {
#Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new TestUrlResource(url);
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
}
Then you need to modify the UrlResource
public class TestUrlResource extends UrlResource {
public TestUrlResource(URL url) {
super(url);
}
#Override
public boolean exists() {
return true;
}
#Override
public File getFile() throws IOException {
return new File(getURL().toString().replace("file:", ""));
}
}
In my current spring, some forms have a field where the user can upload a file, which should be saves inside the folder resources from project (src/main/resources, following the structure created by maven).
the method responsible for save the file in this folder is working ok until this line:
URL path = this.getClass().getClassLoader().getResource(file);
the variable path is staying with the value null. the variable file is defined with this value:
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
Anyone can tell me the right way to do this?
PS.: the complete code for this method is:
public boolean upload_picture(E e, MultipartFile f) {
Integer id = null;
if(f == null) {
return false;
}
Class<?> clazz = e.getClass();
Method methods[] = clazz.getDeclaredMethods();
for(int i=0; i<methods.length; i++) {
if(methods[i].getName().equals("getId")) {
try {
id = (Integer) methods[i].invoke(e);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return false;
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
return false;
} catch (InvocationTargetException e1) {
e1.printStackTrace();
return false;
}
}
}
BufferedImage src;
try {
src = ImageIO.read(new ByteArrayInputStream(f.getBytes()));
} catch (IOException e3) {
e3.printStackTrace();
return false;
}
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
URL path = this.getClass().getClassLoader().getResource(file);
File destination;
try {
destination = new File(path.toURI());
} catch (URISyntaxException e2) {
destination = new File(path.getPath());
e2.printStackTrace();
}
try {
ImageIO.write(src, "jpeg", destination);
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
Needs to redirect the error and exceptions which i found in the catch block to .html page
This is my code now i want if anytime any file not found excpetion will come then it should redirect to .html page or borwser
public class XmlToHtml {
public static void main(String[] args) {
if (args.length == 3 && args.length !=0) {
String dataXML = args[0];
String inputXSL = args[1];
String outputHTML = args[2];
XmlToHtml xmltoHtml = new XmlToHtml();
try {
xmltoHtml.transform(dataXML, inputXSL, outputHTML);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
System.out.println("TransformerConfigurationException" + e);
} catch (TransformerException e) {
e.printStackTrace();
System.out.println("TransformerException" + e);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FileNotFoundException" + e);
}
} else {
System.err.println("Wrong Input");
System.err
.println("Please Enter in the follwing format : Data.xml Input.xsl Output.html");
}
}
public void transform(String dataXML, String inputXSL, String outputHTML)
throws FileNotFoundException, TransformerException,
TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource(inputXSL);
Source xmlDoc = new StreamSource(dataXML);
OutputStream htmlDoc = new FileOutputStream(outputHTML);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlDoc));
Desktop dk = Desktop.getDesktop();
try {
dk.open(new File(outputHTML));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}