public static String[] words = null;
public static String readFile(String name) {
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(name));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
words = everything.split("\\n");//not sure if this is right...
} finally {
br.close();
}
} catch (Exception e) {
e.getMessage();
}
return "Loaded " + i + " words";
}
I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?
The problem is that:
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
sb is never actually appended anything, it is just appending empty strings over and over again.
should be:
while (line != null) {
i++;
sb.append(line);
sb.append("\n");
line = br.readLine();
}
Related
protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}
I am been searching online and on here on how I can remove a line that contains one or two words but I can't find anything on java. This is the code I have right now:
try {
BufferedReader reader = new BufferedReader(new FileReader("Readfile.txt"));
String line = reader.readLine();
while(line !=null)
{
for(int i = 0 ; i<newarray.length;i++){
if(line.contains(newarray[i])){
System.out.println(line);
}
}
line=reader.readLine();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
It reads sentences from a text file, but before it prints them out, I want to delete some sentences that contains a keyword, e.g. fun.
Something like this:
//BufferedReader stuff etc.
List<String> words = new ArrayList<String>();
words.add("fun");
words.add("something");
String line;
while( (line = br.readLine()) != null)
{
boolean found = false;
for(String word: words)
{
if(line.contains(word))
{
found = true;
break;
}
}
if(found) continue;
System.out.println(line);
}
if(line.contains(newarray[i])){
line = line.replace("fun" ,"");
System.out.println(line);
}
Try this it will delete the word before printing it.
I have the following code:
public static void main(String[] args) throws Exception {
String s = "";
StringBuilder sb = new StringBuilder();
File file = new File("C:\\New\\r.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
while(in.readLine() != null) {
sb.append(in.readLine());
}
System.out.println(sb);
s = sb.toString();
byte[] b = s.getBytes();
for(int i = 0; i < b.length; i++) {
if(b[i] == 1){ b[i]=0; }
if(b[i] == 0){ b[i]=1; }
}
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.write(b);
in.close();
fos.close();
dos.close();
}
I get a return of null when I run this program. Maybe I must elevate the program? Help would be appreciated.
Change:
while(in.readLine()!=null)
to:
while((s = in.readLine())!=null)
and then:
sb.append(s);
When you call in your code to in.readLine() twice - you're reading two lines but printing only the second in each iteration.
You're throwing away every odd line:
while(in.readLine()!=null)
{
sb.append(in.readLine());
}
If r.txt only contains one line, you will get the string "null" in the StringBuffer, because the first line of StringBuffer.append does this:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
....
}
If there are two lines, you will get the first line with "null" at the end of the line.
The following will append all lines from the file to the StringBuffer:
String line = null;
while((line = in.readLine()) != null)
{
sb.append(line);
}
your code
while(in.readLine() != null) {
sb.append(in.readLine());
}
change with it
while ((s = in.readLine()) != null)
{
sb.append(s);
}
I have a method that takes data from a .csv file and puts it into an array backwards
(first row goes in last array slot) however I would like the first row in the .csv file to not be in the array. How would I accomplish this? Here is my code thus far:
public static String[][] parse(String symbol) throws Exception{
String destination = "C:/"+symbol+"_table.csv";
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(destination)));
lnr.skip(Long.MAX_VALUE);
String[][] stock_array = new String[lnr.getLineNumber()][3];
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
String strLine = "";
StringTokenizer st = null;
int line = lnr.getLineNumber()-1;
while((strLine = br.readLine()) != null){
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
stock_array[line][0] = st.nextToken();
st.nextToken();
stock_array[line][1] = st.nextToken();
stock_array[line][2] = st.nextToken();
st.nextToken();
st.nextToken();
st.nextToken();
}
line--;
}
}
catch(Exception e){
System.out.println("Error while reading csv file: " + e);
}
return stock_array;
}
You can skip the first line by just reading it in and doing nothing. Do this just before your while loop:
br.readLine();
To make sure that your array is the right size and lines get stored in the right places, you should also make these changes:
String[][] stock_array = new String[lnr.getLineNumber()-1][3];
...
int line = lnr.getLineNumber()-2;
Your code is not efficient, as far as my knowledge goes. Also, you are using linenumberreader.skip(long.max_value), which is not a correct/confirmed way to find the line count of the file. StringTokenizer is kind of deprecated way of splitting tokens. I would code it, in the following way:
public static List<String[]> parse(String symbol) throws Exception {
String destination = "C:/"+symbol+"_table.csv";
List<String[]> lines = new ArrayList<String[]>();
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
int index = 0;
while((line = br.readLine()) != null){
if(index == 0) {
index++;
continue; //skip first line
}
lines.add(line.split(","));
}
if(lines != null && !lines.isEmpty()) {
Collections.reverse(lines);
}
} catch(IOException ioe){
//IOException Handling
} catch(Exception e){
//Exception Handling
}
return lines;
}
I am reading each line of the file in the below way
BufferedReader in = new BufferedReader(new FileReader(inFile));
while (null != (line = in.readLine())) {
}
I want to do some validation in the first line and last line alone. Is there any
way to check if it's a first line and last line inside the while loop
while (null != (line = in.readLine())) {
if(firstlineoffile) {
}
else if (lastlineoffile) {
}
else
{
}
}
Cool question. I played a bit round it and here's an SSCCE, just copy'n'paste'n'run it.
package com.stackoverflow.q2292917;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Test {
public static void main(String... args) throws IOException {
// Create test file.
File file = new File("/test.txt");
PrintWriter writer = new PrintWriter(file);
writer.println("line 1");
writer.println("line 2");
writer.println("line 3");
writer.println("line 4");
writer.println("line 5");
writer.close();
// Read test file.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String next, line = reader.readLine();
for (boolean first = true, last = (line == null); !last; first = false, line = next) {
last = ((next = reader.readLine()) == null);
if (first) {
System.out.println("first line: " + line);
} else if (last) {
System.out.println("last line: " + line);
} else {
System.out.println("normal line: " + line);
}
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
// Delete test file.
file.delete();
}
}
Output:
first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5
I however question the readability and interpretability by starters... ;)
String currentLine = in.readLine();
String nextLine = in.readLine();
boolean hasStarted = false;
while(null != currentLine){
if(!hasStarted){
//first line.
hasStarted = true;
}
//all your processing here.
if(null == nextLine){
//last line, cause there's nothing else coming up
}
currentLine = nextLine;
nextLine = in.readLine();
}
if you add a count, and rearrange your code a little, this should work (I haven't tested this so there may be syntax errros):
int count = 0;
String line = in.readLine();
while (line!=null) {
String currLine = line;
if(count==0){
//currLine is the first line
}
line = in.readLine();
if(line==null){
//currLine is the last line
}
if(count>0 && line!=null){
//do something with lines in between
System.out.println(currLine);
}
count++;
}
public class Vomitfirstline {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("Path"));
br.readLine();
{
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();
}
}
}
Someone might well come up with a more elegant solution than this, but here we go:
boolean isFirstLine = true;
do{
String line = in.readLine();
if(isFirstLine){
//this is the first line
isFirstLine = false;
}
else if(line==null){ //previous line was the last line
in.reset();
line = in.readLine();
//do last line specific stuff
break;
}
else {
//do stuff for lines in between
}
in.mark(100);
}while (line!=null);
I haven't tested this, so there might be minor errors. I haven't sorted out exception handling in this code. readLine(), mark() and reset() throw IOException and mark() can also throw IllegalArgumentException