Reading/storing a text file in java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to read a text file in the following format and store it (java).
The format of the text file is like this:
1111
1010
1100
1000
It's a Hadamard matrix as you can tell. I'm very new to java and can't figure out how to accomplish this. I want to be able to perform computations on the matrix.
Can someone help me with this

This is not tough. you should learn File Handling in java. there is plenty of tutorials over internet. Use Google. I am posting here the code as required. if this helpful vote me up as i needed and accept it as answer. (courtesy: http://www.mkyong.com/)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderWriter {
public static void main(String[] args) {
Reader();
Writer();
}
static void Reader(){
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\matrix.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static void Writer(){
try {
String content = "1010\n1111\n0000\n0101\n";
System.out.println("Writing ... \n"+content);
File file = new File("D:\\matrix.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Java PING a range of IP Address [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 4 years ago.
Improve this question
Java program to ping single IP Address
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PingIP {
public static void runSystemCommand(String command) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}
....
}
But can i ping a range of IP Address with java.
If you're just trying to execute a bash command which pings a range, you're better off to use nmap
A working example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
final List<String> command = new ArrayList<>();
command.add("nmap");
command.add("-T5");
command.add("-sP");
command.add("172.19.0.0-255");
executeCommand(command);
}
private static int executeCommand(final List<String> command) {
try {
final ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash").command(command);
processBuilder.redirectErrorStream(true);
System.out.println("executing: " + processBuilder.command().toString());
final Process process = processBuilder.start();
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
readStream(inputStream);
readStream(errorStream);
return process.waitFor();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return -1;
}
private static void readStream(final InputStream iStream) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(iStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
This could be refactored down to be more specific, but for your basic user case this gives some flexibility.

Not printing to file java [duplicate]

This question already has an answer here:
Java PrintWriter not working
(1 answer)
Closed 6 years ago.
I am trying to log what my program is doing. Currently I'm using PrintWriter but all it produces is a blank txt file. Can someone please correct my code if possible or give any suggestions.
public class Log {
public static void log(String string){
if(string != null) {
System.out.println("log ".concat(string));
try {
PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void log(String[] strings) {
if (strings == null) return;
for(String string : strings) {
if (string != null) {
System.out.println("log ".concat(string));
try {
PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You have to flush the PrintWriter to get data written in the file
PrintWriter out = new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
out.flush();
If you're done with writing into file you should close the PrintWriter which will also cause data to be written
out.close();
You must close the file. Like this:
PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
out.close();
As an aside, you can make your second method much cleaner:
public static void log(String[] strings) {
if (strings == null) return;
for(String string : strings) {
log(string);
}
}
Any time you are copy pasting the same code, you should be looking for a way to use encapsulation / method calls to remove duplicated code. That will make it easier to change things later if you need to.

unexpected exception: java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Example {
public static void main(String[] args) {
BufferedReader input = null;
BufferedWriter output = null;
try{
int c;
input = new BufferedReader(new FileReader("readfile.txt"));
output = new BufferedWriter(new FileWriter("writefile.txt"));
while ((c=input.read())!= -1) {
output.write(c);
}
} catch (FileNotFoundException fnfe){
System.err.println("The file was not found.");
fnfe.getMessage();
} catch (IOException ioe) {
System.err.println("The file could not be read.");
ioe.getMessage();
}finally {
try {
output.close();
} catch (IOException e) {
System.err.println("The file was not opened.");
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
System.err.println("The file couldn't be closed.");
e.printStackTrace();
}
}
}
}
The above code throws an unexpected exception - NullPointerException in one of the try block on the following line:
output.close();.
Can anyone explain the reason for that? Any help would be appreciated. Thanks in advance.
The line
input = new BufferedReader(new FileReader("readfile.txt"));
might throw before output is initialized. Hence output == null when attempting to execute output.close();. Maybe you meant something like this instead:
if (output != null)
output.close();

Code deletes the content of the file rather than replacing a text

In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

How do make output have more than one string (Java)

I asked a similar question before regarding I/O using Java.
I'm trying to copy a list of strings into another file.
package file;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
FileWrite fW = new FileWrite();
try (BufferedReader br = new BufferedReader(new FileReader("B:\\inLarge.dat")))
{
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent, stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}
//fW.serializeAddress("Boston", "Canada");
}
}
And
package file;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
public class FileWrite {
public void serializeAddress(String city, String country){
try
{
File file = new File("B:\\outLarge.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(city + " " + country);
bw.close();
System.out.println("Done");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
But the ending output file has only one result, how do I make it copy everything?
I am thinking buffered-writer somehow needs to be in the loop to write new ones on top of existing ones? But not sure how to implement that.
Thanks a lot.
You are overwriting the file contents every time you call your serialize method, because you didn't open the file in append mode. To prevent overwriting, open the file in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, this is one case where the solution is probably over-engineered. For efficiency you really should be opening your file just once. Here's an example:
public static void main(final String[] args) {
try {
final BufferedReader reader = new BufferedReader(new FileReader("infile.txt"));
final PrintWriter writer = new PrintWriter(new File("outfile.txt"));
String inputLine;
while((inputLine = reader.readLine()) != null) {
writer.println(inputLine);
}
reader.close();
writer.close();
} catch(final Exception e) {
e.printStackTrace();
}
}
You're overwriting the existing file every time you open it. Instead append to it.
Change
FileWriter fw = new FileWriter(file.getAbsoluteFile());
to
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

Categories

Resources