i would like to save in a string multiple lines from reading file, eg: I am reading one file.txt with the following content:
def var x as int.
def var y as char.
procedure something:
//here some content
end.
I would like to catch content between "procedure" and "end".
public static void main(String[] args) {
String piContent = "";
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.contains("procedure")){
piContent = line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I appreciate any help.
final StringBuilder sb = new StringBuilder();
try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
boolean rememberStuff = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("procedure ")) {
rememberStuff = true;
} else if (line.startsWith("end.")) {
rememberStuff = false;
} else if (rememberStuff) {
sb.append(line).append('\n');
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("Lines found between procedure and end:");
System.err.println(sb);
public static String getContentFromFile(Path file) throws IOException {
StringBuilder buf = new StringBuilder();
boolean add = false;
for (String line : Files.readAllLines(file)) {
if ("end.".equalsIgnoreCase(line.trim()))
break;
if (add)
buf.append(line).append(System.lineSeparator());
else if ("procedure something:".equalsIgnoreCase(line.trim()))
add = true;
}
return buf.toString();
}
Related
I want to convert JSON into CSV. I have written the following code; it's working fine for a small JSON file, but for another file (around 43MB), it's not working.
public class JSON2CSV
{
public static void main(String myHelpers[]) throws IOException{
BufferedReader br = null;
String line="";
int i=0;
br = new BufferedReader(new FileReader("tickets_1.txt"));
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
{
i++;
System.out.println("loop"+i);
sb.append(line);
}
String resultstring = sb.toString();
String jsonString = "{\"infile\":"+resultstring+"}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("fromTicketsJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
br.close();
}
}
}
In my app I am displaying the first portion of each line of the CSV in a JList, and when it is selected and a button is pressed (delete) I want it to remove that line from the file based on the first entry. I am trying the method where you have a temp file then write to it then rename it at the end but that isnt working out for some reason. Any ideas?
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Delete service
String selected = (String) jList1.getSelectedValue();
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = new File("/users/aak7133/desktop/temp.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(passwords));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
//String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line);
}
boolean successful = temp.renameTo(passwords);
} catch (Exception e) {
}
updateList();
clearFields();
}
The problem is actually caused by the open reader and writer. This should work:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String selected = (String) jList1.getSelectedValue();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = File.createTempFile("temp", ".txt", new File("/users/aak7133/desktop/"));
reader = new BufferedReader(new FileReader(passwords));
writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
// String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line + "\n");
}
if (passwords.canWrite()) {
try {
reader.close();
reader = null;
} catch (IOException ignore) {}
try {
writer.close();
writer = null;
} catch (IOException ignore) {}
String path = passwords.getAbsolutePath();
passwords.delete();
boolean successful = temp.renameTo(new File(path));
System.out.println(successful);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {}
}
}
updateList();
clearFields();
}
I figured out I needed to put passwords.delete() before temp.renameTo(passwords). This fixed the issue right away.
Hello I'm creating a HangMan game and I want the array list of words to come from the internet. Its not initializing for me. Can anyone help? This is the code.
public String getaword()
{
try
{
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt");
//URLConnection urlConnection = (URLConnection)url.openConnection();
//inStream = new InputStreamReader(urlConnection.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null)
{
lines.add(str);
words = lines.toArray(new String[lines.size()]);
}
}
catch (Exception e)
{
e.getStackTrace();
}
Random r = new Random();
int num;
num = r.nextInt(words.length);
return words[num];
}
Try this.
public static void main(String[] args) {
ArrayList<String> lines = new ArrayList<String>();
try {
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives(929).txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
while((str = in.readLine()) != null) {
lines.add(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(lines);
}
I am finding some difficulties to do the following operation in Java:
I have to take the content of an xml file and print it
I do something like this:
System.out.println("settings.xml: " + ClassLoader.getSystemResourceAsStream("/home/andrea/Documenti/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/src/settings.xml"));
The problem is that the result of this statment is:
settings.xml: null
Why? What can I do to do it?
Tnx
Andrea
You can use this function:
private String getStringFromFile(File file)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((line = br.readLine()) != null)
{
sb.append(line);
}
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
For example:
System.out.println("settings.xml: " + ClassLoader.getSystemResourceAsStream("home/andrea/Documenti/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/src/settings.xml"));
i'm trying to read a web address from a text and then have the app open that address, my buffered reader seems to be reading the lines correctly but readline keeps coming back null
String rsslink = null;
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rsslink = br.readLine()) != null)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
You will get the last line that is null rsslink.
You need to change your loop
try {
while ((rsslink = br.readLine()) != null)
{
}
}
to
try {
StringBuilder sb= new StringBuilder();
while ((rsslink = br.readLine()) != null)
{
sb.append(rsslink);
}
rsslink = sb.toString();
}
Use this:
String rsslink = "";
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink +=line ;
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
Better your StringBuffer orStringBuilder.
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();