i am creating a project in which i need to read a specific line starting from a keyword in .java file .
i will have to read .java files for :
Intent myIntent = new Intent(StudentMap.this, StudentPref.class);
StudentMap.this.startActivity(myIntent);
how will i read these two lines anywhere in the code . should i have to set regex for this but how ?
i am using :
public void onClick(View v) {
TextView responseText = (TextView) findViewById(R.id.responseText);
String myData = "";
String test = "Intent ";
// String name="";
switch (v.getId()) {
case R.id.getExternalStorage:
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null){
myData = myData + strLine;
if (strLine.equals(test)) {
tv1.setText(tv1.getText() + strLine + "\n");
}
else{
tv1.setText(tv1.getText() + "nakaam" + "\n");
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
responseText.setText("MySampleFile.java data retrieved from external Storage...");
break;
}
tv1.setText(tv1.getText() + myData + "\n"+"\n"+"\n"+"end");
//tv1.setText(tv1.getText() + strLine + "\n");
}
as far my knowledge Intent keyword is static in every file so i can get the start of line like "Intent" but how to read this line and the next line only from large file..?
If you want to start your String at the Keyword Intent, and read a Number of Lines after that, you can do something like this:
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int remainingLines = 0;
String stringYouAreLookingFor = "";
for(String line; (line = br.readLine()) != null; ) {
if (line.startsWith("Intent")) {
remainingLines = <Number of Lines you want to read after keyword>;
stringYouAreLookingFor += line
} else if (remainingLines > 0) {
remainingLines--;
stringYouAreLookingFor += line
}
}
}
I guess this should give you an idea on how to search the String you are looking for.
Related
I'm trying to find an object in a list from a text file
Example:
L;10;€10,50;83259875;YellowPaint
-H;U;30;€12,00;98123742;Hammer
G;U;80;€15,00;87589302;Seeds
By inserting 98123742 by input with scanner, i want to find that string.
I tried to do this:
private static void inputCode() throws IOException {
String code;
String line = null;
boolean retVal = false;
System.out.println("\ninsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if (token[0].equals(code) && token[1].equals(code)) {
retVal = true;
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("impossible open the file " + fileName);
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
System.out.println(retVal);
}
How can i print "-H;U;30;€12,00;98123742;Hammer" inserting "98123742" (that is the code of the product) ?
Why are you splitting in the first place? For such a simple usecase, and with that line format, I'd go with
line.contains(";" + code);
Not much else to do.
First, I output the content of the file, here is my code. And then, I will do some string work to edit each line. What if I what to save the changes, how to do it? Can I do it without creating a tmp file?
String executeThis = "cat" + " " + "/var/lib/iscsi/nodes/"
+ iscsiInfo.selectedTargets2.get(i) + "/" + myString + "/default";
String inputThis = "";
Process process = ServerHelper.callProcessWithInput(executeThis, inputThis);
try {
logger.debug("stdOutput for editing targets credential:");
BufferedReader stdOutput = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = stdOutput.readLine()) != null) {
logger.info("The content is########################"+s)
// do something to edit each line and update the file
}
} catch (IOException e) {
logger.fatal(e);
}
The following steps could achieve what you are looking for.
Instantiate a FileWriter object to create a tmp file.
FileWriter fw = new FileWriter("tmp");
Read line by line from the source file.
Modify this line (string object) in memory.
Write out this string in the tmp file.
fw.write(line);
Close the file handles.
Rename the tmp file to the source file name.
sourceFile.renameTo(targetFile);
This question has been answered here. I repeat the answer.
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
String line;String input = "";
while ((line = file.readLine()) != null) input += line + '\n';
System.out.println(input); // check that it's inputted right
// this if structure determines whether or not to replace "0" or "1"
if (Integer.parseInt(type) == 0) {
input = input.replace(replaceWith + "1", replaceWith + "0");
}
else if (Integer.parseInt(type) == 1) {
input = input.replace(replaceWith + "0", replaceWith + "1");
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input);
// write the new String with the replaced line OVER the same file
FileOutputStream File = new FileOutputStream("notes.txt");
File.write(input.getBytes());
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
public static void main(String[] args) {
replaceSelected("Do the dishes","1");
}
I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I was working a little bit with config files and file reader classes in java.
I always read/wrote in the files with arrays because I was working with objects.
This looked a little bit like this:
public void loadUserData(ArrayList<User> arraylist) {
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
String[] userParams = line.split(";");
String name = userParams[0];
String number= userParams[1];
String mail = userParams[2];
arraylist.add(new User(name, number, mail));
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works fine, but how can I save the content of a file as only one single string?
When I read a file, the string I use should be the exact same as the content of the file (without the use of arrays or line splits).
how can I do that?
Edit:
I try to read a SQL-Statement out of a file to use it with JDBC later on. That's why I need the content of the File as a single String
This method will work
public static void readFromFile() throws Exception{
FileReader fIn = new FileReader("D:\\Test.txt");
BufferedReader br = new BufferedReader(fIn);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
String text = sb.toString();
System.out.println(text);
}
I hope this is what you need:
public void loadUserData(ArrayList<User> arraylist) {
StringBuilder sb = new StringBuilder();
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
// String[] userParams = line.split(";");
//String name = userParams[0];
//String number= userParams[1];
//String mail = userParams[2];
sb.append(line);
}
String jdbcString = sb.toString();
System.out.println("JDBC statements read from file: " + jdbcString );
} catch (IOException e) {
e.printStackTrace();
}
}
or maybe this:
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);
Just do that:
final FileChannel fc;
final String theFullStuff;
try (
fc = FileChannel.open(path, StandardOpenOptions.READ);
) {
final ByteBuffer buf = ByteBuffer.allocate(fc.size());
fc.read(buf);
theFullStuff = new String(buf.array(), theCharset);
}
nio for the win! :p
You could always create a Buffered reader e.g.
File anInputFile = new File(/*input path*/);
FileReader aFileReader = new FileReader(anInputFile);
BufferedReader reader = new BufferedReader(aFileReader)
String yourSingleString = "";
String aLine = reader.readLine();
while(aLine != null)
{
singleString += aLine + " ";
aLine = reader.readLine();
}
I have a text file called "Hello.txt"
It has the following contents:
dog
cat
mouse
horse
I want to have a way to check that when reader is reading the lines, if the line equals 2, it replaces "cat" with "hen" and write back to the same file. I have tried this much so far and i dont know where to put the condition to check if line=2, then it does the replacing.My codes are:
import java.io.*;
public class Python_Read_Replace_Line
{
public static void main(String args[])
{
try
{
File file = new File("C:\\Hello.py");
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:\\Hello.txt")));
int numlines = lnr.getLineNumber();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + System.lineSeparator();
}
reader.close();
String newtext = oldtext.replaceFirst("cat", "hen");
FileWriter writer = new FileWriter("C:\\Hello.txt");
writer.write(newtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
The file contents should be something like this:
dog
hen
mouse
horse
The code I posted above works because it just replaces cat with hen. I want to have a condition (line number=2), then it replaces it.
Something like this?
int lineCount = 1;
while((line = reader.readLine()) != null)
{
if (lineCount == 2)
oldText += parseCommand.replaceFirst("\\w*( ?)", "hen\1")
+ System.lineSeparator();
//oldText += "hen" + System.lineSeparator();
else
oldtext += line + System.lineSeparator();
lineCount++;
}
Reference.
You could create a variable to keep track of which line number you are at, like so:
int line = 0;
while((line = reader.readLine()) != null)
if (line == 1)
{
oldtext += line + System.lineSeparator();
}
++line;
}