I have a file with lines of text like this:
[A]
This is one line.
This is another line.
[B]
A third line.
...
and so forth. I want to read this file into Java and look for the lines which only contain [A] etc. for further reference. I tried:
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.texts);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String textstring = new String(b);
String[] textarr = textstring.split("[\\r\\n]+");
And then:
int lineB = 0;
for (int i=0; i<textarr.length; i++) {
if textarr[i].substring(0, 3) == "[B]") lineB = i;
}
Afterwards, line is still zero. First I thought this has something to do with how new lines are handled (I'm using Windows), but I also had no luck with substring(0,3). I want this to give me lineB = 3, any ideas what I'm doing wrong?
Use String#startsWith like this:
int lineB = 0;
for (int i=0; i<textarr.length; i++) {
if (textarr[i].startsWith("[B]"))
lineB = i;
}
Try String.contains(CharSequence s) or String.startsWith(String prefix)
edit: Oh, and try BufferedReader:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line = "";
while ((line = in.readLine()) != null)
if(line.startsWith("whatever")) ...
Related
I'm a beginner and need some help. I'm trying to scan a text file into an array line by line, but omitting one line. My text file is
i am
you are
he is
she is
it is
I want to create a method that will scan this and put elements into an array with an exception for one line (that is chosen by entering the String as a parameter for the method). Then erase the original text file and print there the created array (without that one deleted line). Sorry, I suck at explaining.
I have tried this:
public static void deleteLine(String name, String line) throws IOException {
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = new FileReader(sc + name + ".txt");
Scanner scan = new Scanner(fr);
int n = countLines(name); // a well working method returning the number if lines in the file (here 5)
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine() && !scan.nextLine().equals(line))
listArray[i] = scan.nextLine();
else if (scan.hasNextLine() && scan.nextLine().equals(line))
i--;
else continue;
}
PrintWriter print = new PrintWriter(sc + name + ".txt");
print.write("");
for (int i = 0; i < n-2; i++) {
print.write(listArray[i] + "\n");
}
print.close()
}
I get an error "Line not found" when I enter: deleteLine("all_names","you are") (all_names is the name of the file). I'm sure the problem lies in the for-loop, but I have no idea why this doesn't work. :(
//SOLVED//
This code worked after all. Thanks for answers!
public static void deleteLine(String name, String line) throws IOException{
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = null;
fr = new FileReader(sc+name+".txt");
Scanner scan = new Scanner(fr);
int n = LineCounter(name);
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (!nextLine.equals(line)) {
listArray[i] = nextLine;
}
else i--;
}
}
PrintWriter print = new PrintWriter(sc+name+".txt");
print.write("");
for(int i=0;i<n-1;i++){
print.write(listArray[i]+System.lineSeparator());
}
print.close();
}
You are reading the lines twice scan.nextLine() while comparing and because of that you run out of the lines.
Replace your loop with this one or similar
for (int i = 0; i < n; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (nextLine.equals(line)) {
listArray[i] = nextLine;
}
}
}
Have a look at how you are comparing String objects. You should use the equals method to compare a String's content. Using operators like == and != compares if the String objects are identical.
Now after using equals correctly have a look at how you are using nextLine. Check its Javadoc
I feel LineCounter(name) works because you did not put a ".txt" there. Try removing the ".txt" extension from the file name in the Filereader and Printwriter objects and see if it works. Usually in windows, the extension is not a part of the file name.
Here's an alternative (easier) solution to do what you want, using easier to understand code. (I think)
Also it avoids multiple
loops, but uses a single Java 8 stream to filter instead.
public static void deleteLine(String name, String line) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(name));
lines = lines.stream().filter(v -> !v.equals(line)).collect(Collectors.toList());
System.out.println(lines);
// if you want the String[] - but you don't need it
String[] linesAsStringArr = new String[lines.size()];
linesAsStringArr = lines.toArray(linesAsStringArr);
// write the file using our List<String>
Path out = Paths.get("output.txt"); // or another filename you dynamically create
Files.write(out, lines, Charset.forName("UTF-8"));
}
I have a text file which is a game save for my java game (cookie clickers) so the stuff in the file will be numbers without spaces. Like so:
10
20
30
40
50
I need to read the lines and save each one to its string.
So the strings should be like this, so I can use them a lot easier:
lives = 10
kills = 20
score = 30
...
The saving code will be in its class file (Save.class). I only need the code, other stuff should not be a problem.
Is there some kind of easy way to make it work as I want?
You can use a Scanner as follows:
Scanner s = new Scanner(new File("your file"));
String lives = s.nextLine();
String kills = s.nextLine();
String score = s.nextLine();
...
s.close();
Scanner is good here.
List<String> list = new LinkedList<>();
Scanner scan = new Scanner(new File("the_file"));
while (scan.hasNextLine())
list.add(scan.nextLine());
I recommend you to use an ArrayList. Like this:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now you will have stored all the lines of your file so you can access each of them like this:
for(int i = 0; i < list.size(); i++)
{
System.out.println("The content of the line " + i + " it's " + list.get(i);
}
I expect it will be helpful for you!
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
String line = null;
int index = 0;
while((line = reader.readLine()) != null) {
if(index == 0) {
line1 = line;
} else if(index == 1) {
line2 = line;
} else if(index == 2) {
line3 = line;
}
index++;
}
or you could read the text and save it as string array
also you might would like to use this http://ini4j.sourceforge.net
Use readAllLines:
File data = new File("textfile.txt");
List<String> lines = Files.readAllLines(data.toPath());
This way of saving game state smells. It seems that you're on your way on reinventing the wheel. Why don't you use a properties file where you can save the key(lives, kills, score) and the value ? It would make the code a lot more readable.
String gameStateFile = "gameState.properties";
Properties gameProperties = new Properties();
gameProperties.load(input);
String lives = gameProperties.get("lives");
I have a text file (called data.txt, which has 350 lines)
How can I find the text on a given line of the file? For example:
int imageVariable = 5;
String imageText = nthLineOfFile(imageVariable);
textView1.setText(imageText);
I'm trying to write the String nthLineOfFile(int image) function.
Thanks
You may try this:
String str = FileUtils.readLines(file).get(lineNumber);
or you may use the conventional way by using BufferedReader class:
BufferedReader r = new BufferedReader(new FileReader(file));
for (int i = 0; i < lineNumber - 1; i++)
{
r.readLine();
}
return r.readLine();
You can use Scanner:
Scanner fileIn = new Scanner(your file);
for (int i = 0; i < lineNum - 1; i++) {
fileIn.nextLine(); // ignore
}
nthLine = fileIn.nextLine();
I have a text file i already read it and return an array of string "lines" in this structure
{(1),text,(2),text,(3),text........}
I want to restructure it as
{(1)text,(2)text,(3)text........}
which mean concatenate every number like (1) with the next text and so on
public String[] openFile() throws IOException {
FileInputStream inStream = new FileInputStream(path);
InputStreamReader inReader = new InputStreamReader(inStream,"UTF-8");
BufferedReader textReader = new BufferedReader(inReader);
int numberOfLine = countLines();
String[] textData = new String[numberOfLine];
for (int i = 0; i < numberOfLine; i++) {
// if (textReader.readLine()!= null) {
textData[i] = textReader.readLine();
//}
}
textReader.close();
return textData;
}
how can i do it please using Java language ?
Thanks for your helps and your opinions
String[] newArray = new String[textData.length / 2];
for (int i = 0; i < textData.length - 1; i+=2) {
newArray[i / 2] = textData[i] + textData[i + 1];
}
But be sure that your textData has an even length
Put this snippet before the return statement and return newArray instead;
It seems that the comma you want to omit is always preceded by a closing bracket. Assuming that that is the only time it happens in your string you could just do a simple replacement in your for-loop:
textData[i] = textData[i].replace("),", ")");
If that isn't the case, then another thing you could do is work on the basis that the comma you want to remove is the first in the string:
//Locate index of position of first comma in string
int firstComma = x.indexOf(',');
//Edit string by concatenating the bit of the string before the comma
and the bit after it, stepping over the comma in the process
textData[i] = (textData[i].substring(0, firstComma)).concat(textData[i].substring(firstComma + 1));
I am new to Java. I have one text file with below content.
`trace` -
structure(
list(
"a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)),
"b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.379787,-0.105249,1.0063,0.613083,-0.165703,0.695775))
)
)
Now what I want is, I need to get "a" and "b" as two different array list.
You need to read the file line by line. It is done with a BufferedReader like this :
try {
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int lineNumber = 0;
double [] a = null;
double [] b = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
lineNumber++;
if( lineNumber == 4 ){
a = getDoubleArray(strLine);
}else if( lineNumber == 5 ){
b = getDoubleArray(strLine);
}
}
// Close the input stream
in.close();
//print the contents of a
for(int i = 0; i < a.length; i++){
System.out.println("a["+i+"] = "+a[i]);
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Assuming your "a" and"b" are on the fourth and fifth line of the file, you need to call a method when these lines are met that will return an array of double :
private static double[] getDoubleArray(String strLine) {
double[] a;
String[] split = strLine.split("[,)]"); //split the line at the ',' and ')' characters
a = new double[split.length-1];
for(int i = 0; i < a.length; i++){
a[i] = Double.parseDouble(split[i+1]); //get the double value of the String
}
return a;
}
Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.
You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:
Array[] first= line.split("("); //first[2] will contain the values
Then:
Array[] arrayList = first[2].split(",");
You will have the numbers in arrayList[]. Be carefull with the final brackets )), because they have a "," right after. But that is code depuration and it is your mission. I gave you the idea.