How to read a file? - java

private void getInput() throws IOException {
InputStream resourceAsStream = this.getClass().getResourceAsStream(
"aaa.txt");
BufferedReader br = new BufferedReader(new FileReader(
resourceAsStream.toString()));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} finally {
br.close();
}
}
The file aaa.txt is in the same project and it cannot be read, I have java.lang.NullPointerException when I execute that.

Only do this
BufferedReader br = new BufferedReader(new FileReader("aaa.txt"));
But put the file in the filereader instead.
Hope it helpt.

Related

How do I skip the first element from a String Array?

How do I skip the first element from a String Array?
Another quick approach is to control the line reads through flag like below:
public List<Beruf> fileRead(String filePath) throws IOException {
List<Beruf> berufe = new ArrayList<Beruf>();
String line = "";
try {
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
Boolean firstLine = Boolean.TRUE;
while ((line = reader.readLine()) != null) {
if(firstLine) {
firstLine = Boolean.FALSE;
continue;
}
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return berufe;
}
The easiest way to remove the header line would be to just read it before you enter your while loop.
String filePath = path;
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
String headers = reader.readLine(); //This removes the first line from the BufferedReader
while ((line = reader.readLine()) != null) {
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
If you use java 8 or higher and are allowed to use streams you could also use the lines method of the Files class
Files.lines(Paths.get(filePath))
.skip(1) // skipping the headers
.map(line -> line.split(";"))
.map(attributes -> createBeruf(attributes))
.forEach(beruf -> berufe.add(beruf));

How to handle CWE-400-Resource exhaustion error

We are getting an IBM APPSCAN exception for the following code.
{
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
Can someone suggest a way to handle the same.
I myself have figured out the solution for this.
Just we need to limit the character read by readline().
there is no way to limit the same, so we need to use BoundedBufferedReader.
Try the below:
{
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
StringBuilder sb = new StringBuilder();
String line;
BoundedBufferedReader boundedReader = new BoundedBufferedReader(br,204800,204800);
while (( line = boundedReader.readLine() ) != null) {
sb.append(line+"\n");
}
br.close();

How to read content from a text zip file?

This prints everything one one line. My original text file has different lines. How to still get the content line by line after the file is zipped? I am working on Mac.
public static void main(String[] args) throws IOException {
QuickTest mfe = new QuickTest();
ZipFile zip = new ZipFile("test.txt.zip");
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
System.out.println(entry.getName());
if (!entry.isDirectory()) {
if (FilenameUtils.getExtension(entry.getName()).equals("txt")) {
StringBuilder out = getTxtFiles(zip.getInputStream(entry));
System.out.println(out.toString());
}
}
}
System.out.println("Done");
}
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
} catch (IOException e) {
// do something, probably not a text file
e.printStackTrace();
}
return out;
}
Inside your method:
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
The following loop:
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
reads lines but the Java readLine() method does not append an end-of-line character. You'll need to add a newline (or carriage return for the Mac) to see lines.
try {
while ((line = reader.readLine()) != null) {
out.append(line);
out.append( '\n' );
}

How to display all lines of text from a file instead of stopping at the end of a line?

The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}

Reading an InputStream in Java

I'm new to Java thus the question,
I'm using the following class to read a file into a string.
public class Reader {
public static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
How can I modify the method signature of read to read a InputStream as opposed to a string.
Remove the String argument and create an argument of type InputStream. Pass this argument to the constructor of an InputStreamReader and this InputStreamReader can be passed to the constructor of your BufferedReader.
public static String readFile(InputStream is) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
.
.
.
}
Maybee you want to try a try-with-resource statement. Then you can remove the final block. It looks like this.
public static String readFile(InputStream is) throws IOException
{
try (BufferedReader br = new BufferedReader(new InputStreamReader(is)))
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
}
}
If it is not for educational purposes, don't do this manually. E.g. you could use IOUtils.toString from Apache Commons.

Categories