JEditorpane cannot load URL - java

I have problem with my JEditorPane, cannot load URL, always show java.io.FileNotFoundException. Totally I am confused how to solve it.
JEditorPane editorpane = new JEditorPane();
editorpane.setEditable(false);
String backslash="\\";
String itemcode="a91000mf";
int ctr=6;
File file = new File("file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode+"&jumlah="+String.valueOf(ctr)+"&lokasi=../images");
if (file != null) {
try {
//editorpane.addPropertyChangeListener(propertyName, listener)
editorpane.setPage(file.toURL());
System.out.println(file.toString());
} catch (IOException e) {
System.err.println(e.toString());
}
} else {
System.err.println("Couldn't find file: TextSamplerDemoHelp.html");
}
I just put "file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode", but it will show its same error : cannot open file, but I can open it in my browser

File expects a local file path, but "file://...." is a URI... so try this:
URI uri = new URI("file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode+"&jumlah="+String.valueOf(ctr)+"&lokasi=../images");
File file = new File(uri);

You should remove all usage of the File class.
A string which starts with "file:" is a URL, not a file name. It is not a valid argument to a File constructor.
You are calling the JEditor.setPage method which takes a URL, not a File. There is no reason to create a File instance:
try {
URL url = new URL("file:///C:/Development/project2/OfflineSales/test/index.html?item_code=" + itemcode + "&jumlah=" + ctr + "&lokasi=../images");
editorpane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
JEditorPane also has a convenience method which does the conversion of a String into a URL for you, so you can even skip the use of the URL class entirely:
String url = "file:///C:/Development/project2/OfflineSales/test/index.html?item_code=" + itemcode + "&jumlah=" + ctr + "&lokasi=../images";
try {
editorpane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
(Notice that String.valueOf is not needed. It is implicitly invoked whenever you concatenate a String with any object or primitive value.)

Related

How to write and constantly update a text file in Android

I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}

how to save text to file in Android Studio?

I want to create file in which the first line will be constantly updated. actually I want to save this file to custom path, for example /storage/emulated/0/Download, but I don't know how to do that, so now I have something like this:
public void save(){
while(true) {
try {
String FILENAME = "my_file";
String string = "" + System.currentTimeMillis();
FileOutputStream fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(string.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
and this code gives me two errors
Cannot resolve method 'openFileOutput'
Cannot resolve symbol 'MODE_PRIVATE'
FileOutputStream fos = getApplicationContext().getContextResolver().openFileOutput(FILENAME);
Before using openFileOutpout() you have to use getContextResolver() and there is no Context.MODE_PRIVATE parameter in this function

Access file using Java in Windows with illegal Character in path

I am using a Windows machine and Java. I'm just trying to backup a file, but I ran into an issue with an illegal character in the path ("#"). I really tried and I'm stuck. I rewrote it trying all the variations I could find or think of. Any help would be greatly appreciated.
public class SyncActionMachine {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, URISyntaxException {
String MSI_one, MSI_two, dropBox;
GetDate getDate = new GetDate();
MSI_one = "C:\\Users\\Brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\Q2965ZS7\\localhost\\ActionMachine.sol";
MSI_two = "C:\\Users\\Brian\\Desktop\\test.txt";
dropBox = "C:\\Users\\Brian\\Dropbox\\Action Machine History\\ActionMachine.sol";
File source = new File(MSI_one);
File destination = new File(dropBox);
// Attempt #1 using string with special characters
try {
Files.copy(source.toPath(), destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #2 using URI - not really sure how to use it.
URI uri;
uri = new URI("file:///C:/Users/Brian/AppDate/Roaming/Macromedia/Flash%20Player/%23SharedObjects/Q2965ZS7/localhost/ActionMachine.sol");
Path uriSelfMadePath = Paths.get(uri);
try {
Files.copy(uriSelfMadePath, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #3 Suggestion from Aurasphere. Thanks again for quick response.
// Not sure what I'm suppose to do with the URL
String thePath = MSI_one;
thePath = URLEncoder.encode(thePath, "UTF-8");
Path aurasphereThePath = Paths.get(thePath);
try {
Files.copy(aurasphereThePath, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Attempt #4 build path using Patha and passing in augruments separately
Path pathOneByOne = Paths.get("C:", "Users", "Brian", "AppDate", "Roaming", "Macromedia", "Flash Player",
"#SharedObjects", "Q2965ZS7", "localhost", "ActionMachine.sol");
try {
Files.copy(pathOneByOne, destination.toPath());
} catch (IOException iOException) {
System.out.println("Didn't work: " + iOException);
}
// Seeing what all these path's look like
URL fileUrl = source.toURI().toURL();
URI fileUri = source.toURI();
System.out.println("------------Path Print out------------------");
System.out.println("URLEncoder : " + thePath);
Path from = Paths.get(fileUri);
System.out.println("URL : " + fileUrl);
System.out.println("URI : " + fileUri);
System.out.println("source: " + source);
}
}
Thanks for any advice.
Just use URLEncode:
String thePath = "your_path";
thePath = URLEncoder.encode(thePath, "UTF-8");
Thank you everyone that looked and commented. Must have been some sleep derived moment. Anyway here is the source, it worked fine. Turned out # was a big deal, I'm not even sure what my hang up was.
public static void main(String[] args) throws IOException, URISyntaxException {
String MSI_one, MSI_two, dropBox;
GetDate getDate = new GetDate();
MSI_one = "C:\\Users\\Brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\Q2965ZS7\\localhost\\ActionMachine.sol";
MSI_two = "C:\\Users\\brian\\AppData\\Roaming\\Macromedia\\Flash Player\\#SharedObjects\\HSTARDTM\\localhost\\ActionMachine.sol";
dropBox = "C:\\Users\\brian\\Dropbox\\Action Machine History\\";
// Create new file name for backup file
dropBox = dropBox + "ActionMachine-" + getDate.today() + ".sol";
File source = new File(MSI_two);
File destination = new File(dropBox);
copyNewFile cf = new copyNewFile(source, destination);
}
public class copyNewFile {
public copyNewFile(File source, File dest) throws IOException {
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(source.toPath(), dest.toPath(), options);
System.out.println("File sucessfully copied.");
}
}

Read file from SVN over https using svnkit

SVN server is accessible over https. So I need to read a file that is located there. I followed the snippet from svnkit wiki (http://svn.svnkit.com/repos/svnkit/tags/1.3.5/doc/examples/src/org/tmatesoft/svn/examples/repository/DisplayFile.java), but my SVNKindNode is NONE and as a result no file is read. Nevertheless there's no exceptions during connection. So I can assume that I do connect correctly to SVN server, but then something goes wrong.
Here is the code:
public class SVNRepoConnector {
private String username = "user";
private String password = "pwd";
private String baseUrl = "https://mysvnserver.com/svn/project/trunk";
private String filePath = "/myproject/src/main/webapp/file.html";
public void downloadSchema() {
DAVRepositoryFactory.setup();
SVNRepository repository = null;
try {
repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(baseUrl));
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(username, password);
repository.setAuthenticationManager(authManager);
SVNNodeKind nodeKind = repository.checkPath(filePath, -1);
if(nodeKind == SVNNodeKind.NONE) {
System.err.println("There is file at: " + baseUrl + filePath);
System.exit(1);
} else if (nodeKind == SVNNodeKind.DIR) {
System.err.println("The entry at " + baseUrl + filePath + " is a directory while a file was expected.");
System.exit(1);
}
SVNProperties properties = new SVNProperties();
ByteArrayOutputStream out = new ByteArrayOutputStream();
repository.getFile(filePath, -1, properties, out);
System.out.println("Content:\n");
try {
out.writeTo(System.out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (SVNException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SVNRepoConnector connector = new SVNRepoConnector();
connector.downloadSchema();
}
}
I receive "There is file at..." due to SVNNodeKind equals NONE. I cannot understand what is wrong here. How to read file from SVN over https?
Btw, my svnkit is 1.8.5.
Specify a relative path (unless baseUrl is the repository root):
private String filePath = "myproject/src/main/webapp/file.html";
instead of
private String filePath = "/myproject/src/main/webapp/file.html";
I found the solution after thorough debugging of the sources.
In short, the problem is in the second argument of repository.checkPath(filePath, -1); and repository.getFile(filePath, -1, properties, out);. filePath must be file name and path to it must be in the baseUrl field. After these changes everything started working correctly.
Regarding the snippet, in case of www/license.html, one should pass 1 as a second arg.

Using JSoup to save the contents of this url: http://www.aw20.co.uk/images/logo.png to a file

I am try to use JSoup to get the contents of this url http://www.aw20.co.uk/images/logo.png, which is the image logo.png, and save it to a file. So far I have used JSoup to connect to http://www.aw20.co.uk and get a Document. I then went and found the absolute url for the image I am looking for, but now am not sure how to this to get the actual image. So I was hoping someone could point me in the right direction to do so? Also is there anyway I could use Jsoup.connect("http://www.aw20.co.uk/images/logo.png").get(); to get the image?
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JGet2 {
public static void main(String[] args) {
try {
Document doc = Jsoup.connect("http://www.aw20.co.uk").get();
Elements img = doc.getElementsByTag("img");
for (Element element : img) {
String src = element.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is: " + src);
if (src.contains("logo.png") == true) {
System.out.println("Success");
}
getImages(src);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void getImages(String src) throws IOException {
int indexName = src.lastIndexOf("/");
if (indexName == src.length()) {
src = src.substring(1, indexName);
}
indexName = src.lastIndexOf("/");
String name = src.substring(indexName, src.length());
System.out.println(name);
}
}
You can use Jsoup to fetch any URL and get the data as bytes, if you don't want to parse it as HTML. E.g.:
byte[] bytes = Jsoup.connect(imgUrl).ignoreContentType(true).execute().bodyAsBytes();
ignoreContentType(true) is set because otherwise Jsoup will throw an exception that the content is not HTML parseable -- that's OK in this case because we're using bodyAsBytes() to get the response body, rather than parsing.
Check the Jsoup Connection API for more details.
Jsoup isn't designed for downloading the content of the url.
Since you are able to use a third party library, you can try apache common IO for downloading the content of a given URL to file using:
FileUtils.copyURLToFile(URL source, File destination);
It is only one line.
This method does not work well. Please careful when using it.
byte[] bytes = Jsoup.connect(imgUrl).ignoreContentType(true).execute().bodyAsBytes();
You can use these methods or part of these methods to solve your problem.
NOTE: IMAGE_HOME is the absolute path. e.g. /home/yourname/foldername
public static String storeImageIntoFS(String imageUrl, String fileName, String relativePath) {
String imagePath = null;
try {
byte[] bytes = Jsoup.connect(imageUrl).ignoreContentType(true).execute().bodyAsBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
String rootTargetDirectory = IMAGE_HOME + "/"+relativePath;
imagePath = rootTargetDirectory + "/"+fileName;
saveByteBufferImage(buffer, rootTargetDirectory, fileName);
} catch (IOException e) {
e.printStackTrace();
}
return imagePath;
}
public static void saveByteBufferImage(ByteBuffer imageDataBytes, String rootTargetDirectory, String savedFileName) {
String uploadInputFile = rootTargetDirectory + "/"+savedFileName;
File rootTargetDir = new File(rootTargetDirectory);
if (!rootTargetDir.exists()) {
boolean created = rootTargetDir.mkdirs();
if (!created) {
System.out.println("Error while creating directory for location- "+rootTargetDirectory);
}
}
String[] fileNameParts = savedFileName.split("\\.");
String format = fileNameParts[fileNameParts.length-1];
File file = new File(uploadInputFile);
BufferedImage bufferedImage;
InputStream in = new ByteArrayInputStream(imageDataBytes.array());
try {
bufferedImage = ImageIO.read(in);
ImageIO.write(bufferedImage, format, file);
} catch (IOException e) {
e.printStackTrace();
}
}
Also is there anyway I could use Jsoup.connect("http://www.aw20.co.uk/images/logo.png").get(); to get the image?
No, JSoup will only get text and such but cannot be used to download files or binary data. That being said, just use the file name and path that you've gotten through JSoup and then use standard Java I/O to download the file.
I've used NIO to do the downloading. i.e.,
String imgPath = // ... url path to image
String imgFilePath = // ... file path String
URL imgUrl;
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
imgUrl = new URL(imgPath);
rbc = Channels.newChannel(imgUrl.openStream());
fos = new FileOutputStream(imgFilePath);
// setState(EXTRACTING + imgFilePath);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (rbc != null) {
try {
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources