I'm making application which needs to read strings from file on FTP Server. I use apache.commons.net.FTPClient for it. I have following code:
Log.e("sizzeee", String.valueOf(mClient.listFiles().length));
InputStream stream=mClient.retrieveFileStream(f.getName());
DataInputStream in=new DataInputStream(stream);
BufferedReader buf=new BufferedReader(new InputStreamReader(in));
List<String> tasks=new ArrayList<String>();
String s;
while ((s=buf.readLine())!=null) {
tasks.add(s.trim());
}
stream.close();
in.close();
buf.close();
Log.e("sizzeee", String.valueOf(mClient.listFiles().length));
That works correctly, but I have some problems: last Log instruction shows "0" files in current directory! But first Log instruction shows "6" files. Therefore I think that I don't close file stream or something else. Please, inform me about my mistake. Thank you
Related
I have been trying to invoke a Python 3.x program from Java. What I need is to get output from python and write it to a file. This is what I have done. This is creating a Json file but does not gives the output. Please help me out here.
public static void main(String[] args) throws ScriptException, IOException {
Process p = Runtime.getRuntime().exec("python <path to the file>/reg.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println(ret);
BufferedWriter out = new BufferedWriter(new FileWriter("<some path>/output.json"));
out.write(ret);
out.close();
}
Ok, so after our talk in the comments, your script throws an error because it cannot find a file output.txt. Now, the thing is that this is logged to an error stream not the regular one. What you should do is to open that stream and read it:
BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
In fact, you could open both streams: errorStream and outputStream and read error stream first to check if it contains something (it means that execution failed). If it doesn't, open outputStream and read its contents normally.
I am implementing my own HTTP server using sockets. In my java project folder I have a folder /root where all the files are saved which can be downloaded (test.html, test.jpg), so when the user browses to let's say localhost:8080/test.html my server takes the file, reads it and sends the bytes to the client's browser ,setting the right headers. Everything works fine with the .html extension but I have a problem with the images...the browser says that the file cannot be shown properly.
Here is the class which I use to read the bytes from the file:
public class FileRequestHandler {
public FileRequestHandler(){
}
/*
* Method which reads a text-file and turns it into a string
*/
public String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
}
after executing readFile() I get a string(I will call it response).
Now I set the headers and send them to the client:
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: image/jpeg");
out.println("Content-Length: " + response.length());
out.println();
out.println(response);
out.flush();
out is a PrintWriter object.
As I already mentioned, this method works with a html-file and everything is shown. What am I doing wrong? Maybe the encoding of the raw-bytes is incorrect or the headers were set incorrectly?
Thank you for the help!
An image is not a text file. Yet you are apparently reading it as text using a BufferedReader. That will mangle it ... and the use of readLine() and the line reassembly mangles it some more.
Either way, the browser will be unable to decode the mangled image that your server is sending.
You should use InputStream / OutputStream subtypes rather than Reader / Writer subtypes, and you should NOT attempt to convert the image into a string at any point.
(It is also a bad idea to attempt to implement an HTTP server using socket-level I/O ... but that's a different issue.)
BufferedReader reader = new BufferedReader(new FileReader (file));
The problem starts here. Readers and Writers are for text. Images are not text. You should be using an input stream, and writing bytes directly to an output stream, not collecting them in a String.
I'm trying to read a system file on the Nexus 5 and rewrite it to a second file with some modifications I will make. The problem is even without my modifications the file is not written completely. Il gets almost to the end and then stops writing always at the same place. Stops at line 450 and only writes <path name when it should write <path name="voice-tty-full-headphones"> and continue for 30 more lines...
Strangely if I export to a textview everything is there so the problem is not when reading the file but when writing to the new one. I have attached a copy of the file i'm working with along with a copy of the file thats being generated. I really have no idea what to try from here.
//Output File
File outputFile = new File(Environment.getExternalStorageDirectory().getPath(), "/xxx/mixer_paths.xml");
outputFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(outputFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
//Input File
File internalStorage = Environment.getRootDirectory();
File inputFile = new File(internalStorage,"/etc/mixer_paths.xml");
BufferedReader br = new BufferedReader(new FileReader(inputFile));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null )
{
text.append(line+"\n");
}
myOutWriter.append(text);
textView.setText(text);
https://www.dropbox.com/s/7p1cgu7ziyzydh1/mixer_paths_original.xml
https://www.dropbox.com/s/zs03xt4k52vetek/mixer_paths_new.xml
Thanks
Did you forget to close the writer? I've made this mistake myself. Always close your readers and writers when you are done with them. It frees up the resources and in the case of the writer, makes sure to finish writing!
I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.
Here's the code I used, I get no errors or warnings but the file is empty, I created the aq.txt file and placed it in the workspace and it also shows in the project. I'm sure it's something stupid I'm missing but I just can't figure it out. Also, I tried all the other questions but the suggested answer is closing the stream and/or flushing it, both of which I do but they don't seem to work. Any help would be greatly appreciated!
Writer writer = null;
FileOutputStream fos= null;
try{
String xyz= "You should stop using xyz";
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getFilesDir()+File.separator+"aq.txt")));
writer.write(xyz);
writer.flush();
}
catch(IOException e) {
System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
if(writer != null){
try {
writer.close();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Try like this:
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(xyz);
writer.flush();
Context class provides a helper method Context.openFileOutput(String name, int mode) that will return a FileOutputStream to you for a file located in your applications Files directory.
I don't see any immediate reason why your way would not work, but I know I've used this other way successfully.
EDIT: After re-reading your question I think you are confused about where this file is going to be written to. It will not get written to the project folder inside of your workspace. This is going to be written to the internal storage of the android device that you run it on. Every application gets its own chunk of storage space located at \data\data\[package-name]\Files\ Your file is going to get written to there so you won't be able to immediately open it up and see the contents of it (unless your device is rooted.) You will instead have to open it up with java code and print its contents to the Log or some other output method in order to verify that your write did/did not work.
EDIT 2: Reading the file
FileInputStream in = openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Log.d("TAG", line);
This will read and output to the log the first line of the file.
This will certainly work :
File file = new File("fileName");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data to write in the file.");
writer.flush();