I have put a file "template.html" inside RAW folder and I want to read it into a InputStream. But it is returning me null. Can't understand what is wrong in the below code
e.g. fileName passed as parameter is "res/raw/testtemplate.html"
public String getFile(String fileName) {
InputStream input = this.getClass().getClassLoader().getResourceAsStream(fileName);
return getStringFromInputStream(input);
}
Also, there might be a better solution by putting these files in a particular subfolder and putting it inside Asset folder but then I believe I would need to pass context in AssetManager. I don't understand that solution, sorry I am new to android development. Can someone shed some light regarding how this approach can be achieved.
EDIT
I have started implementing this solution with Assets. Below method is supposed to return a string containing the entire text of the file stored as template.html.
getFile("template.html") // I am sending extension this time
Problem getting error getAssets() is undefined.
public String getFile(String fileName) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
String line;
try {
reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
use this
new BufferedInputStream(getResources().openRawResource(filepath));
this will return a buffered input stream
The file name should be without extension :
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("raw/FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
For this purposes uses assets folder:
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.
So, you could easy get access at assets with context: context.getAssets()
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("filename.txt")));
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
Related
I'm trying to upload zip file to the url https://anypoint.mulesoft.com/designcenter/api-designer/projects/{projectId}/branches/master/import. Content-Type must be application/zip, cant change to multipart/form-data. In Mule 3, a java transform class is used (com.test.FileReader) with the FileReader.class is stored in lib. It worked in Mule 3.
I tried to use ReadFile component to read test.zip and set as payload but it's not working. Any suggestion how to upload zip file in Mule 4?
package com.test;
import org.mule.transformer.*;
import org.mule.api.*;
import org.mule.api.transformer.*;
import java.io.*;
public class PayloadFileReader extends AbstractMessageTransformer
{
public Object transformMessage(final MuleMessage message, final String outputEncoding) throws TransformerException {
byte[] result = null;
try {
result = this.readZipFile("test.zip");
}
catch (Exception e) {
e.printStackTrace();
}
message.setPayload((Object)result);
return message;
}
public String readFileTest(final String path) throws FileNotFoundException, IOException, Exception {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = null;
final StringBuilder stringBuffer = new StringBuilder();
try {
bufferReader = new BufferedReader(fileReader);
String line;
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
finally {
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
return stringBuffer.toString();
}
public byte[] readZipFile(final String path) {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final byte[] b = new byte[(int)file.length()];
try {
final FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
fileInputStream.close();
}
catch (FileNotFoundException e) {
System.out.println("Not Found.");
e.printStackTrace();
}
catch (IOException e2) {
System.out.println("Error");
e2.printStackTrace();
}
return b;
}
}
'
Assuming that your zip file corresponds to a valid API spec, in Mule 4, you don't need to use a custom java code to achieve what you want: you can read the file content using the File connector Read operation, and use an HTTP Request to upload it to Design Center using Design Center API. Your flow should look like:
For the Read operation, you only need to set the file location, in the File Path operation property.
No need to set content type in the HTTP Request (Mule 4 will configure the content type automatically based on the file content loaded by the Read operation).
You can't use Java code that depends on Mule 3 classes in Mule 4. Don't bother trying to adapt the code, it is not meant to work. Their architecture are just different.
While in Mule 4 you can use plain Java code or create a module with the SDK, there is no reason to do so for this problem and it would be counterproductive. My advise it to forget the Java code and resolve the problem with pure Mule 4 components.
In this case there doesn't seem a need to actually use Java code. The File connector read operation should read the file just fine as it doesn't appear the Java code is doing anything else than reading the file into the payload.
Sending through the HTTP Request connector should be straightforward. You didn't provide any details of the error, (where is it happening, complete error message, HTTP status error code, complete flow with the HTTP request in both versions, etc) and the API Designer REST API doesn't document an import endpoint so it is difficult to say if the request is correctly constructed.
My problem is as follows. Currently I`m doing a web crawling project for my final year. I want to crawl down web pages carrying out .org domains and archive for text mining. Having said about the background.
During the crawling process number of blank .org domain carrying websites also were detected. Is there any criteria we could use to refrain from crawling web sites having no content?
Currently I am passing the URL and it reads the URLs HTML content in Java. Although websites do not carry any content, still it has HTML code. So could you please suggest me a way of doing it?
I have tried figuring out text availability, image availability but it was not possible to stop 100% blank web pages detection.
Finally I was able to detect blank web pages depends on its size (below 3 KB) and by scanning the content. Firstly I download the HTML content via URLConnection and store it in memory.
public ArrayList<String> captureHtmlTags(String inputUrl) {
ArrayList<String> readWebsiteHTMLTags = new ArrayList<String>();
try {
URL url = new URL(inputUrl);
try {
URLConnection connection = url.openConnection();
// open the stream and assign it into buffered reader..
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
if (bufferedReader.readLine() != null) {
while ((inputLine = bufferedReader.readLine()) != null) {
Document doc = Jsoup.parse(inputLine);
readWebsiteHTMLTags.add(String.valueOf(doc));
}
bufferedReader.close();
readWebsiteHTMLTags.size();
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return readWebsiteHTMLTags;
}
Then using iText 7 library I convert read HTML into PDF and scan for text contents.
public String convertWebsiteToPdf(ArrayList<String> htmlCode) {
String generateHtmlPage = null;
String fileLocation = CONST_FILE_PATH; // path to save the PDFs
generateHtmlPage = htmlCode.toString();
FileOutputStream fileOutputStream = null;
try {
try {
fileOutputStream = new FileOutputStream(fileLocation);
HtmlConverter.convertToPdf(generateHtmlPage, fileOutputStream);
fileOutputStream.close();
} catch (Exception e) {
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return fileLocation;
}
If no content found along with the low size of file, I consider it as a Blank web page.
It worked out finally.
I am using Netbeans on OS X and cannot seem to write text to a text file that I have in a package named "assets".
Below is the way I tried to accomplish writing to the text file and so far my method of doing this is not working.
The way I tried to approach this problem was converting a string to url, then converting the url to a uri. Then I used the uri for the new file parameter. After I tried to write a string using the class print writer.
public class Experiment {
File createFile(String path) {
java.net.URL url = getClass().getResource(path);
URI uri;
try {
uri = url.toURI();
}
catch (URISyntaxException e) {
uri = null;
}
if ((url != null) && (uri != null)) {
System.out.println("file loading sucess");
return new File(uri);
}
else {
System.out.println("Error file has not been loaded");
return null;
}
}
File file = createFile("/assets/myfile.txt");
public static void main(String[] args) {
Experiment testrun = new Experiment();
try {
PrintWriter writer = new PrintWriter(new FileWriter(testrun.file));
writer.println("it works");
writer.flush();
writer.close();
System.out.println("string was written");
}
catch (IOException e) {
System.out.println("there was an error while writing");
}
}
}
The output given from my try catch statements say that the file write code was executed.
file loading sucess
string was written
BUILD SUCCESSFUL (total time: 2 seconds)
I have also tried using absolute string paths for making a new file, but with null results. I am running out of ideas and hoping for some guidance or solution from somebody.
It seems a really stupid thing but I can't see what I am doing wrong.
I have a folder that contains several zip files. Every zip file contains at least one file named sometingXYZsomething. I want to read every file sometingXYZsomething without unzipping every single zip, so, on the fly let's say.
My code is:
try (Stream<Path> paths = Files.walk(Paths.get(FOLDER_NAME)))
{
paths
.filter(p -> p.toString().contains("XYZ"))
.forEach(p -> readFileXYZ(Paths.get(p.getName())));
}
catch (IOException e)
{
e.printStackTrace();
}
And
private static void readFileXYZ(Path pathFile)
{
try {
Files.lines(pathFile).forEach(System.out::println);
} catch (IOException ex)
{
ex.printStackTrace();
}
}
The test folder has one zip, that contains a txt document testFileXYZ.txt and I get this exception
java.nio.file.NoSuchFileException: testFileXYZ.txt
testFileXYZ.txt
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
How can I get a stream of the txt file in the zip without extracting it?
The problem you've got is that you're not actually unzipping the content of the ZipFile. The ZipFile.stream() allows you to iterate through the Zip metadata (the list of file names in the Zip) but doesn't actually unzip the content for you to read. To do that, you need to use an InputStream acquired from the ZipFile, and then read that to get your content. I've provided an example of this below. There are other ways of doing this (e.g. using a ZipInputStream) but I wanted to base my example on the code you supplied. Hope this helps!
private static void openZip(String zipPath)
{
try (ZipFile zipFile = new ZipFile(zipPath))
{
zipFile.stream()
.filter(p -> p.toString().contains("XYZ"))
.forEach(p -> readFileXYZ(p, zipFile));
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void readFileXYZ(ZipEntry zipEntry, ZipFile zipFile)
{
try {
InputStream inputStream = zipFile.getInputStream(zipEntry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
I know that this is a widely discussed question , but I am really confused with those examples provided on android developers manual .
So , I have a "source.txt" in my res/raw folder .For example I want to write 2 lines in it(for ex. Hello\nWorld) and then read them from another activity. Can anyone write the source code for this , please.
You should replace your .txt file to your extornal or internal storage.And You must give permission for write text from androidManifest.xml
for reading file you can do this
public String readFile(String filePath) {
String jString = null;
StringBuilder builder = new StringBuilder();
File yourFile = new File("/sdcard/" + filepath);
if (yourFile.exists()) {
Log.i("file", "file founded");
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(yourFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String row = "";
try {
while ((row = bufferedReader.readLine()) != null) {
builder.append(row + "\n");
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jString = builder.toString();
}
else {
Log.i("FAIL", "FILE NOT FOUND");
}
return jString;
}
for writing file you can use this
public void writetoFile(String filename,String text) {
File file = new File("/sdcard/" + filename);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileWriter fileWriter;
try {
//you can change second parametre true or false this is about append or clean and write
fileWriter = new FileWriter(file, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append(jsonText);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Whatever is in your APK file is read-only, therefore you are unable to write to file stored in res/raw source folder as it is still in your APK. if you want to work on file shipped with your app, you need to copy if to internal storage or SD card from APK first so that would allow you to alter the content.
Every file in your apk is read only, so you need to create the file in your internal storage or SD Card. If you just want to send small amount to of data to second activity, you can send data along with intent or use sharedPreference.
If you really want to read and write data to/from SD card then you need to use FileInputStream and OutputStreamWriter to read/write data to a file. Check this tutorial here to see how it's done. http://www.java-samples.com/showtutorial.php?tutorialid=1523