Writing the contents to a file from input stream - java

I want to write the inputstream into a file in java. How to write the contents into a text file in java?
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//I want to write the content to a file line by line here
while (!in.ready()) {}
System.out.print("'\n");
in.close();
}

FileWriter fstream = new FileWriter("fileName");
BufferedWriter fbw = new BufferedWriter(fstream);
while ((line = in.readLine()) != null) {
fbw.write(line + "\n");
}

Related

Read textfile line by line

I tried it this way but it doesn't find the textfile.
try {
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
All files are in the same package.
Your text file is inside a the package "trainer" which is inside "src" so when you request it, you must use "src/trainer/textfile.txt". The preceding / denotes the root of the application and is optional if you're not exporting to runnable jars for example.
FileInputStream fstream = new FileInputStream("src/trainer/textfile.txt");

Android/java Cant read from .txt file in local storage

So i have a .txt file in local storage its a simple text file. The text is basically just a series of lines.
I am using the code below to attempt to read the text file (i verify the file exists before calling this method).
public static String GetLocalMasterFileStream(String Operation) throws Exception {
//Get the text file
File file = new File("sdcard/CM3/advices/advice_master.txt");
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
System.out.print(text.toString());
return text.toString();
}
The code produces in the log
----Determined that file is readable
But that is the ONLY output the file data is not written to the log
Also i have tried inserting before the while loop the following to attempt to just read the first line
line = br.readLine();
System.out.println("-----" + line);
That produces the following output:
-----null
Check this out getExternalStorage
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
Try to add a lead slash in file path /sdcard/CM3/advices/advice_master.txt
File file = new File("/sdcard/CM3/advices/advice_master.txt");
Try this. Just pass the txt file name as a parameter...
public void readFromFile(String fileName){
/*
InputStream ips;
ips = getClass().getResourceAsStream(fileName);
//reading
try{
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine())!=null){
//reading goes here ;)
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
*/
// or try this
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
Let me refine my answer. You can try another way to read all lines from advice_master.txt and see what happens. It makes sure that all file contents can be read.
Charset charset = Charset.forName("ISO-8859-1");
try {
List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}

Not entering while loop

I'm trying to write in a file whatever the user has written.
The file creates and all but the program fails to write whatever the user wrote from the program, to the file (The program is like notepad). It wont enter the while loop because the String line is null even if I write something in my program.
It seems it's returning null when I print the "line" String after using br.readLine().
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
Full code:
try {
path = fileChooser.getSelectedFile().getAbsolutePath().replace('\\', '/')
+ "/";
File file = new File(path + File.separator +
JOptionPane.showInputDialog(null, "File name", "File") + ".txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
bw.flush();
bw.close();
textArea.append(path);
} catch(IOException e1) {
e1.printStackTrace();
}
file.createNewFile();
. . .
BufferedReader br = new BufferedReader(new FileReader(file));
The reader works from an empty file that just has been created. Of course br.readLine() will return null immediately since the file is empty.
Instead of the while loop, I would simply write:
bw.write(textArea.getText());

Can not write all the data to txt file

I have a problem with writing data to my .txt file. It doesn't write all the data to my .txt file. I have tried it to put everything in a array, but also that doesn't works.
My code:
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
writer = new BufferedWriter(new FileWriter(" the path .."));
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
It writes only the last line of the console.
By re-creating the object without closing it during every iteration of the loop, you are discarding what you have written so far (You have to use writer.close() to save what you have written using the object).
You will need to declare writer before the loop, so change it to the following
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
writer = new BufferedWriter(new FileWriter(" the path .."));
while ((line = input.readLine()) != null) {
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
Can I just ask, why were you re-declaring the writer object every iteration?

Reading a variable number of lines from a file

I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer

Categories

Resources