Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Let's say I have a file that contains these information
1, 2, 3, 4
5, 6, 7, 8
now how can I ask the program to write ONLY 4 (which is the end of the first line) to a different file. But here's the trick, NOT depending on the user's input.
so after the program ends, the other file would contain
4
I tried trimming the Line (String=String1.trim()) and using the function endsWith() but I need to put a String inside these parentheses.
I started java 3 weeks ago, so please bear with me, thanks.
Use split()
String line = in.nextLine(); // read a line
String[] tokens = line.split("[\\s,]+"); // splits the line into an array
out.write(tokens[tokens.length - 1]); // print the last index of the array.
You can use the split() function to split a line on a separator into a String array. So:
String x = "1,2,3,4";
String[] split = x.split(",");
now the split array contains the individual items, and you can get the last one like this:
String last = split[split.length - 1];
Read the file, line by line
for each line, split the string (String.split()) with space and then access the last element in the array returned by split()
Write the element to the new File (see BufferedWriter and FileWriter).
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
if(line.Trim().endsWith( "4" )){
stringBuffer.append(line);
stringBuffer.append("\n");
}
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
// write the buffer content to new file.
File file = new File("newfile.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are two ways to do this:
The easy way: use myString.subString(myString.length()-1)
The complex/professional way (overkill for your case but just for reference): Use a regex pattern like this.
final String input = "1, 2, 3, 4";
final Pattern pattern = Pattern.compile("(.)\\s*$");
final Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
Where the pattern used means:
(.) - ()capture .any single char
\\s* - followed by 0 or more white-space chars
$ - followed by the end of line
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My text file is in the following format having different type of strings such as below:
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
I would like to remove everything except simple words such as the ones below.
smoldering
temperature
That is if a word is even followed by a comma (e.g. smoldering,), I would remove it.
I tried to remove the digits for a start with MyString.replaceAll("^\\d", " ") but even that is not working.
If you load the entire file into memory, with line breaks, you can use a regex like this:
text = text.replaceAll("(?m)^.*[^a-zA-Z\r\n].*(?:\R|$)", "")
Output
candle
smoldering
temperature
For demo see regex101.
It would however be better to do the filtering while you load the text file:
Pattern simpleWord = Pattern.compile("\\p{L}+"); // one or more Unicode letters
try (BufferedReader in = Files.newBufferedReader(Paths.get("path/to/file.txt"))) {
for (String line; (line = in.readLine()) != null; ) {
if (simpleWord.matcher(line).matches()) {
// found simple word
}
}
}
If you want the simple words in a list, you can simplify that with Java 8 stream:
List<String> simpleWords;
try (Stream<String> lines = Files.lines(Paths.get("path/to/file.txt"))) {
simpleWords = lines.filter(Pattern.compile("^\\p{L}+$").asPredicate())
.collect(Collectors.toList());
}
This solution will iterate over the input.txt lines and paste them into output.txt if they match certain regex. After that it will remove output.txt and rename it with input.txt original file.
Class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Pattern;
public class ReplaceWithRegex {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (Pattern.matches("^[a-zA-Z]+$", line)) {
writer.write(line);
writer.newLine();
}
}
}
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename output to input");
}
} else {
throw new IOException("Could not delete original input file ");
}
}
}
Input.txt
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
Input.txt after execution:
candle
smoldering
temperature
Assuming lines are delimiters:
myString.replaceAll("^[^a-z&&[^A-Z]]*$", "");
I'm importing a file into my code and trying to print it. the file contains
i don't like cake.
pizza is good.
i don’t like "cookies" to.
17.
29.
the second dont has a "right single quotation" and when I print it the output is
don�t
the question mark is printed out a blank square. is there a way to convert it to a regular apostrophe?
EDIT:
public class Somethingsomething {
public static void main(String[] args) throws FileNotFoundException,
IOException {
ArrayList<String> list = new ArrayList<String>();
File file = new File("D:\\project1Test.txt");//D:\\project1Test.txt
if(file.exists()){//checks if file exist
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
String line;
while( (line = reader.readLine()) != null) {
list.add(line);
}
for(int i = 0; i < list.size(); i ++){
System.out.println(list.get(i));
}
}
}}
it should print as normal but the second "don't" has a white block on the apostrophe
this is the file I'm using https://www.mediafire.com/file/8rk7nwilpj7rn7s/project1Test.txt
edit: if it helps even more my the full document where the character is found here
https://www.nytimes.com/2018/03/25/business/economy/labor-professionals.html
It’s all about character encoding. The way characters are represented isn't always the same and they tend to get misinterpreted.
Characters are usually stored as numbers that depend on the encoding standard (and there are so many of them). For example in ASCII, "a" is 97, and in UTF-8 it's 61.
Now when you see funny characters such as the question mark (called replacement character) in this case, it's usually that an encoding standard is being misinterpreted as another standard, and the replacement character is used to replace the unknown or misinterpreted character.
To fix your problem you need to tell your reader to read your file using a specific character encoding, say SOME-CHARSET.
Replace this:
InputStreamReader input = new InputStreamReader(fileStream);
with this:
InputStreamReader input = new InputStreamReader(fileStream, "SOME-CHARSET");
A list of charsets is available here. Unfortunately, you might want to go through them one by one. A short list of most common ones could be found here.
Your problem is almost certainly the encoding scheme you are using. You can read a file in most any encoding scheme you want. Just tell Java how your input was encoded. UTF-8 is common on Linux. Windows native is CP-1250.
This is the sort of problem you have all the time if you are processing files created on a different OS.
See here and Here
I'll give you a different approach...
Use the appropriate means for reading plain text files. Try this:
public static String getTxtContent(String path)
{
try(BufferedReader br = new BufferedReader(new FileReader(path)))
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
}catch(IOException fex){ return null; }
}
package com.testing;
import java.io.BufferedReader;
import java.io.FileReader;
public class CsvParser {
public static void main(String[] args) {
String csvFile = "D:/code-home/SentimentAnalysis/test_data/Sentiment Analysis Dataset.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = "\t"; // data is in format splitted by tab
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] tweet = line.split(cvsSplitBy);
System.out.println(tweet[1]);
System.out.println(tweet[3]);
}
}
}
The program's purpose is to parse the CSV format. I have used bufferRead method.
When I go to compile the program, it works fine. When I run the program,output is printed but there is a exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at com.testing.CsvParser.main(CsvParser.java:34)
First of all: Arrays in Java are Zero-indexed, which means that the first element in an array is not selected by array[1] but by array[0]. Since your OutOufBoundsException is fired at the index 1, your array has at most one element in it (you shoulds check for the size of the array before accessing it). Because you are trying to access the index 3 (fourth element in Java) in the very next line i suspect you expect at least 3 elements in each line. Since there is at most one element you seem to either be using the wrong splitcharacter or your file is not formatted as you expect it to be. I hope this helps you. Kind regards
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have 3 text files that all contain strings from objects.
I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?
You can use:
String[] lines = secondFileText.split("\n");
P.s.- If that doesn't work try replacing \n with \r\n.
You can split a string into lines:
String[] lines = s.split("\r?\n");
Then you can access the line at any index:
System.out.println(lines[0]); // The array starts at 0
Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").
BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadByLine {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File f = new File("xyz.txt");
int lineNumber = 666;
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
int count = -1;
try {
while((line = br.readLine())!=null){
count++;
if (count == lineNumber){
//get the line, do what you want
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
br = null;
}
}
//do what you want with the line
}
}
Let's say I have a series of numbers like...
1 2 3 4
5 6 7 8
9 0
How could I step through each int, but stop when I reach a new line? I'm currently using nextInt() and I know that nextLine() will detect the new line, but I'm not sure how to piece that together. Is it best to take the entire line, and parse the string into separate ints? Or is there a more fluid method of doing this?
For my example, I would want the program to store 1 2 3 4, 5 6 7 8, 9 0 all in their own separate array.
For more clarification, I'm using the java.util.Scanner and I'm reading a text file.
If you want to use Scanner, read the entire line into a String, and then construct a Scanner on the String.
You can open the text file in read mode and read the entire line with readLine() method.
Then you can split the line read with the space ( ' ' ) character which will automatically give you an array.
You can do this till the end of file.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
delimiter = " ";
int myArr[];
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
myArr = strLine.split(delimiter);
// store this array into some global array or process it in the way you want.
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Hope this helps.