Printwriter making newlines out of spaces - java

I have a Reader reading in a file to edit it and save it afterwards with a printwriter.
The start input is like this
The problem is, that sometimes whitespaces are mistaken for new lines somehow like here. I goes even further in cutting it again after the first time
like this
I have tried some different split characters, like (what it actually is (you can see in System.out.println)) but I can´t get it to work properly
The Original loaded Textfile is this and the output of the getText is this
if (lastClicked != 0) {
String path;
switch (lastClicked) {
case 1:
path = "data/alyxia_status.got";
break;
case 2:
path = "data/mog_status.got";
break;
case 3:
path = "data/telias_status.got";
break;
default:
path = "data/tiernen_status.got";
}
String text = textPane.getText();
String toWrite = text.substring(44, text.length() - 16);
System.out.println(toWrite);
String[] parts = toWrite.split("<br>");
FileWriter fileWriter;
try {
fileWriter = new FileWriter(path);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(parts[0]);
for (int i = 1; i<parts.length; i++) {
if (parts[i] != "" && parts[i] != " ") {
printWriter.println();
printWriter.print(parts[i]);
}
}
printWriter.close();
} catch (IOException e1) {
e1.printStackTrace();
System.err.println("Saving failed");
}
}//end if
It should just split on the string "<br>" and not on white spaces that are in between (in System.out.println it´s showing "Base" and then in a newline "Damage")

The following code runs fine for me, try to invoke the printToFile method and pass your String array to is as a parameter. By isolating the problematic code in a separate method it should be much easier to debug. I've also noticed you are comparing String objects with operators, this is not advised and doesn't do what you think it does. Read this answer for more information.
public static void printToFile(String path, String[] output) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter(path);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(output[0]);
for (int i = 1; i < output.length; i++)
{
/* DO NOT compare string with opeators like "!=" or "==,
* instead use equals method to properly compare them
*/
if (!output[i].equals("") && !output[i].equals(" ")) {
printWriter.println();
printWriter.print(output[i]);
}
}
printWriter.close();
}
catch (java.io.IOException e1) {
e1.printStackTrace();
System.err.println("Saving failed");
}
}
public static void main(String[] args) throws IOException
{
Path path = Paths.get("sample.txt");
String[] text = new String[] { "these ", " lines ", "should", " be ", " in new ", "line" };
printToFile(path.toString(), text);
Files.readAllLines(path).forEach(System.out::println);
}
Output
these
lines
should
be
in new
line
Edit: What #DodgyCodeException mentioned in the comments could be the actual cause of your problem. For visibility sake I will just paste the comment:
The first 44 characters of the text are discarded because of your text.substring(44, text.length() - 16);. This includes everything up to "-- Base" (just before "Damage").
Complete solution
I've written a full solution to your problem in the following code. Try the code and see if it works for you then read the explanation posted underneath the code:
public class Main {
/**
* Use {#link StringBuilder} to build a single {#code String}
* from the read contents of file located under given path.
*
* #param path {#code Path} of the file to read
* #throws IOException if an I/O error occurs reading from the file
* or a malformed or unmappable byte sequence is read.
*/
private static String getInputFileContent(Path path) throws IOException {
StringBuilder sb = new StringBuilder();
Files.readAllLines(path).forEach(sb::append);
return sb.toString();
}
/**
* #return the matched content contained in <body> tag within
* the provided text or {#code null} if there was no match.
*/
private static #Nullable String getHTMLBodyFromText(String text) {
Pattern pattern = Pattern.compile("(?:\\s*?<body>)(?:\\s*)((.*\\s)*)</body>");
Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.group(1) : null;
}
public static void printToFile(Path path, String output) {
String toWrite = getHTMLBodyFromText(output);
if (toWrite == null) {
System.err.println("Unable to find body");
return;
}
String[] parts = toWrite.split("<br>");
FileWriter fileWriter;
try {
fileWriter = new FileWriter(path.toString());
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(parts[0]);
for (int i = 1; i < parts.length; i++)
{
/* DO NOT compare string with opeators like "!=" or "==,
* instead use equals method to properly compare them
*/
if (!parts[i].equals("") && !parts[i].equals(" ")) {
printWriter.println(parts[i]);
printWriter.print(parts[i]);
}
}
printWriter.close();
}
catch (java.io.IOException e1) {
e1.printStackTrace();
System.err.println("Saving failed");
}
}
public static void main(String[] args) throws IOException
{
Path inputPath = Paths.get("input.txt");
Path outputPath = Paths.get("output.txt");
printToFile(outputPath, getInputFileContent(inputPath));
}
}
I've used Regex to find the text contained within the <body> tag of the input file you provided (the actual content we want is located in group 1) which was the part that was causing this problem. If you are further interested to see how the pattern included in this code works see this demo.
The rest of your code works fine so all you have to do is call the printToFile method and pass the return value of textPane.getText() as output String argument and it will process and print the required result for you to the text file located under a path of your choosing.

Related

How do I write a method that has an ArrayList and an int as a parameter and returns an ArrayList

I get multiple errors when writing the header of a method that takes an array list and an integer as input.
I have tried several different ways of writing the header for the method. The body is good and gives me what I want but I can't get the header/call name (I don't know what you call the first line of a method) to not throw errors
/**
* Creates Arraylist "list" using prompt user for the input and output file path and sets the file name for the output file to
* p01-runs.txt
*
*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the path to your source file: ");
String inPath = scan.nextLine(); // sets inPath to user supplied path
System.out.println("Please enter the path for your source file: ");
String outPath = scan.nextLine() + "p01-runs.txt"; // sets outPath to user supplied input path
ArrayList<Integer> listRunCount = new ArrayList<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
/**
* Reads data from input file and populates array with integers.
*/
FileReader fileReader = new FileReader(inPath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// file writing buffer
PrintWriter printWriter = new PrintWriter(outPath);
System.out.println("Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts the string to
* an integer and adds the integer to the array
*/
File file = new File(inPath);
Scanner in = new Scanner(file);
String temp=null;
while (in.hasNextLine()) {
temp = in.nextLine();
temp = temp.replaceAll("\\s","");
int num = Integer.parseInt(temp);
list.add(num);
}
listRunCount.findRuns(list, RUN_UP);
//********************************************************************************************************
public ArrayList<Integer> findRuns(ArrayList<Integer> list, int RUN_UP){
returns listRunCount;
}
error messages
Multiple markers at this line
- Syntax error on token "int", delete this token
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Integer cannot be resolved to a variable
- ArrayList cannot be resolved to a variable
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Illegal modifier for parameter findRuns; only final is permitted
- Syntax error, insert ") Expression" to complete CastExpression
- Syntax error on token "findRuns", = expected after this token
- Syntax error, insert "VariableDeclarators" to complete
LocalVariableDeclaration
- Syntax error, insert ";" to complete Statement
This sort of thing removes the need for statics. If you run your code from within the static method main() then all class methods, member variables, etc that are called or referenced from within main() must also be declared as static. By doing:
public class Main {
public static void main(String[] args) {
new Main().run();
}
}
eliminates the need for statics. In my opinion to properly do this the run() method within the class should also be passed the args[] parameter:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
// You project code here
}
}
That way any Command Line arguments passed to the application can also be processed from within the run() method. You will find that most people won't use the method name run for this sort of thing since run() is a method name more related to the running of a Thread. A name like startApp() is more appropriate.
public class Main {
public static void main(String[] args) {
new Main().startApp(args);
}
private void startApp(String[] args) {
// You project code here
}
}
With all this in mind your code might look something like this:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
String runCountFileCreated = createListRunCount();
if (!runCountFileCreated.equals("") {
System.out.println(The count file created was: " + runCountFileCreated);
}
else {
System.out.println(A count file was NOT created!);
}
}
/**
* Creates an ArrayList "list" using prompts for the input and output file
* paths and sets the file name for the output (destination) file to an
* incremental format of p01-runs.txt, p02-runs.txt, p03-runs.txt, etc. If
* p01 exists then the file name is incremented to p02, etc. The file name
* is incremented until it is determined that the file name does not exist.
*
* #return (String) The path and file name of the generated destination
* file.
*/
public String createListRunCount() {
String ls = System.lineSeparator();
File file = null;
Scanner scan = new Scanner(System.in);
// Get the source file path from User...
String sourceFile = "";
while (sourceFile.equals("")) {
System.out.print("Please enter the path to your source file." + ls
+ "Enter nothing to cancel this process:" + ls
+ "Source File Path: --> ");
sourceFile = scan.nextLine().trim(); // User Input
/* If nothing was entered (just the enter key was hit)
then exit this method. */
if (sourceFile.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// See if the supplied file exists...
file = new File(sourceFile);
if (!file.exists()) {
System.out.println("The supplied file Path/Name can not be found!." + ls
+ "[" + sourceFile + "]" + ls + "Please try again...");
sourceFile = "";
}
}
String destinationFile = "";
while (destinationFile.equals("")) {
System.out.print(ls + "Please enter the path to folder where data will be saved." + ls
+ "If the supplied folder path does not exist then an attempt" + ls
+ "will be made to automatically created it. DO NOT supply a" + ls
+ "file name. Enter nothing to cancel this process:" + ls
+ "Destination Folder Path: --> ");
String destinationPath = scan.nextLine();
if (destinationPath.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// Does supplied path exist. If not then create it...
File fldr = new File(destinationPath);
if (fldr.exists() && fldr.isDirectory()) {
/* Supplied folder exists. Now establish a new incremental file name.
Get the list of files already contained within this folder that
start with p and a number (ex: p01-..., p02--..., p03--..., etc)
*/
String[] files = fldr.list(); // Get a list of files in the supplied folder.
// Are there any files in the supplied folder?
if (files.length > 0) {
//Yes, so process them...
List<String> pFiles = new ArrayList<>();
for (String fileNameString : files) {
if (fileNameString.matches("^p\\d+\\-runs\\.txt$")) {
pFiles.add(fileNameString);
}
}
// Get the largest p file increment number
int largestPnumber = 0;
for (int i = 0; i < pFiles.size(); i++) {
int fileNumber = Integer.parseInt(pFiles.get(i).split("-")[0].replace("p", ""));
if (fileNumber > largestPnumber) {
largestPnumber = fileNumber;
}
}
largestPnumber++; // Increment the largest p file number by 1
// Create the new file name...
String fileName = String.format("p%02d-runs.txt", largestPnumber);
//Create the new destination File path and name string
destinationFile = fldr.getAbsolutePath() + "\\" + fileName;
}
else {
// No, so let's start with p01-runs.txt
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
else {
// Supplied folder does not exist so create it.
// User Confirmation of folder creation...
JFrame iFrame = new JFrame();
iFrame.setAlwaysOnTop(true);
iFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFrame.setLocationRelativeTo(null);
int res = JOptionPane.showConfirmDialog(iFrame, "The supplied storage folder does not exist!"
+ ls + "Do you want to create it?", "Create Folder?", JOptionPane.YES_NO_OPTION);
iFrame.dispose();
if (res != 0) {
destinationFile = "";
continue;
}
try {
fldr.mkdirs();
}
catch (Exception ex) {
// Error in folder creation...
System.out.println(ls + "createListRunCount() Method Error! Unable to create path!" + ls
+ "[" + fldr.getAbsolutePath() + "]" + ls + "Please try again..." + ls);
destinationFile = "";
continue;
}
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
ArrayList<Integer> list = new ArrayList<>();
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the writer. */
try (PrintWriter printWriter = new PrintWriter(destinationFile)) {
System.out.println(ls + "Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts
* the string to an integer and adds the integer to the List.
*/
String temp = null;
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the reader. */
try (Scanner reader = new Scanner(file)) {
while (reader.hasNextLine()) {
temp = reader.nextLine().replaceAll("\\s+", "");
/* Make sure the line isn't blank and that the
line actually contains no alpha characters.
The regular expression: "\\d+" is used for
this with the String#matches() method. */
if (temp.equals("") || !temp.matches("\\d+")) {
continue;
}
int num = Integer.parseInt(temp);
list.add(num);
}
// PLACE YOUR WRITER PROCESSING CODE HERE
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
/* return the path and file name of the
destination file auto-created. */
return destinationFile;
}
}

Editing existing txt file in java

I have class Account which have username, fullName, password, id and points.
All accounts are saved in a file.I have many accounts in my file, not just one. This is example of one account in text file.
Miljan9602 Rakita Miljan miljan123 1463433398614 0.0
username, full name, password, id and points
Now, for example if i want to change points for my username. First thing i would do is go through all lines in file and compare all usernames, if i find equal username. I would change point's. This is my idea how to do it. Just dont know how to edit it in file.
public void edit(String username, double points)
{
File f = new File("Accounts.txt");
// file doesnt exist, return from method
if(!f.exists())
return;
Scanner sc = null;
try
{
sc = new Scanner(f);
while(sc.hasNextLine())
{
String line = sc.nextLine(); // Take whole line
String split[] = line.split(" "); // Split it so i can check username
if(split[0].equals(username))
{
String change = Double.toString(points); // Make string from double
split[5] = change; // on fifth index are points
/* My question is now how to edit file and to replace my new points
* with old points ?
* Miljan9602 Rakita Miljan miljan123 1463433398614 0.0 <- Need to change this 0.0 with split[4];
*/
}
}
}catch(Exception e)
{
e.printStackTrace();
}finally{
// finally will always close file
sc.close();
}
You could use the Apache's Commons IO library. Everything you'll need, and more, can be found there. Also, here is the GitHub mirror of Commons IO. Worth a look through.
{
File f = new File("Accounts.txt");
FileWriter fw = new FileWriter(f);
// file doesnt exist, return from method
if(!f.exists())
return;
Scanner sc = null;
try
{
sc = new Scanner(f);
while(sc.hasNextLine())
{
String line = sc.nextLine(); // Take whole line
String split[] = line.split(" "); // Split it so i can check username
if(split[0].equals(username))
{
String change = Double.toString(points); // Make string from double
split[5] = change; // on fifth index are points
/* My question is now how to edit file and to replace my new points
* with old points ?
* Miljan9602 Rakita Miljan miljan123 1463433398614 0.0 <- Need to change this 0.0 with split[4];
*/
for(int i = 0; i < spit.length(); i++{
fw.write(split[i] + " ");
}
System.getProperty("line.separator");
}
}
}catch(Exception e)
{
e.printStackTrace();
}finally{
// finally will always close file
sc.close();
fw.close();
}
This should work
As one has to write the entire read text back to the file system, use Files.readAllLines().
Path path = Paths.get(".../Accounts.txt");
Charset charset = StandardCharsets.UTF_8;
List<String> lines = new ArrayList<>();
if (Files.exists()) {
Files.readAllLines(path, charset);
for (int i = 0; i < lines.size(); ++i) {
String split[] = lines.get(i).split(" ");
if (split[0].equals(username)) {
String change = String.valueOf(points);
split[5] = change; // on fifth index are points
StringBuilder sb = new StringBuilder();
for (String value : split) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(value);
}
lines.set(i, sb.toString()); // Changes the line.
Files.write(path, lines, charset);
break; // leave loop
}
}
}
More explained
To alter a single line of a text file, one in principle has to load the entire text and after altering the line, safe it entirely.
The reason is that the file can shrink or grow, depending on the line changes.
Even with some twists this is not optimal.
Files.readAllLines is a nice method for that. One might also change the format:
Fixed length records (lines) allow a RandomAccessFile. However a text risks being manually edited so the file gets corrupted, and one also has limited field lengths.
The .properties format allows access with the Properties class. Requirement is a key, and a format key = value. Also the text has some escaping (\).
One could keep Accounts.txt in core, say in a class Accounts, representing all as a Map from user name to Account.
class Account {
public final String userName; // Unmodifiable key
public String password;
...
}
class Accounts {
private Map<String, Account> accountsByUserName = new HashMap<>();
public void loadAccounts() throws IOException { ... }
public void saveAccounts() throws IOException { ... }
public Optional<Account> getAccountByUserName(String userName) { ... }
public void deleteAccountByUserName(String userName) { ... }
public void createAccount(Account account) throws AlreadyExistsException { ... }
}

How can I read from the next line of a text file, and pause, allowing me to read from the line after that later?

I wrote a program that generates random numbers into two text files and random letters into a third according the two constant files. Now I need to read from each text file, line by line, and put them together. The program is that the suggestion found here doesn't really help my situation. When I try that approach it just reads all lines until it's done without allowing me the option to pause it, go to a different file, etc.
Ideally I would like to find some way to read just the next line, and then later go to the line after that. Like maybe some kind of variable to hold my place in reading or something.
public static void mergeProductCodesToFile(String prefixFile,
String inlineFile,
String suffixFile,
String productFile) throws IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(prefixFile)))
{
String line;
while ((line = br.readLine()) != null)
{
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(productFile, true))))
{
out.print(line); //This will print the next digit to the right
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
}
}
}
}
EDIT: The digits being created according to the following. Basically, constants tell it how many digits to create in each line and how many lines to create. Now I need to combine these together without deleting anything from either text file.
public static void writeRandomCodesToFile(String codeFile,
char fromChar, char toChar,
int numberOfCharactersPerCode,
int numberOfCodesToGenerate) throws IOException
{
for (int i = 1; i <= PRODUCT_COUNT; i++)
{
int I = 0;
if (codeFile == "inline.txt")
{
for (I = 1; I <= CHARACTERS_PER_CODE; I++)
{
int digit = (int)(Math.random() * 10);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.print(digit); //This will print the next digit to the right
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
if ((codeFile == "prefix.txt") || (codeFile == "suffix.txt"))
{
for (I = 1; I <= CHARACTERS_PER_CODE; I++)
{
Random r = new Random();
char digit = (char)(r.nextInt(26) + 'a');
digit = Character.toUpperCase(digit);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.print(digit);
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
//This will take the text file to the next line
if (I >= CHARACTERS_PER_CODE)
{
{
Random r = new Random();
char digit = (char)(r.nextInt(26) + 'a');
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.println(""); //This will return a new line for the next loop
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
}
System.out.println(codeFile + " was successfully created.");
}// end writeRandomCodesToFile()
Being respectfull with your code, it will be something like this:
public static void mergeProductCodesToFile(String prefixFile, String inlineFile, String suffixFile, String productFile) throws IOException {
try (BufferedReader prefixReader = new BufferedReader(new FileReader(prefixFile));
BufferedReader inlineReader = new BufferedReader(new FileReader(inlineFile));
BufferedReader suffixReader = new BufferedReader(new FileReader(suffixFile))) {
StringBuilder line = new StringBuilder();
String prefix, inline, suffix;
while ((prefix = prefixReader.readLine()) != null) {
//assuming that nothing fails and the files are equals in # of lines.
inline = inlineReader.readLine();
suffix = suffixReader.readLine();
line.append(prefix).append(inline).append(suffix).append("\r\n");
// write it
...
}
} finally {/*close writers*/}
}
Some exceptions may be thrown.
I hope you don't implement it in one single method.
You can make use of iterators too, or a very simple reader class (method).
I wouldn't use List to load the data at least I guarantee that the files will be low sized and that I can spare the memory usage.
My approach as we discussed by storing the data and interleaving it. Like Sergio said in his answer, make sure memory isn't a problem in terms of the size of the file and how much memory the data structures will use.
//the main method we're working on
public static void mergeProductCodesToFile(String prefixFile,
String inlineFile,
String suffixFile,
String productFile) throws IOException
{
try {
List<String> prefix = read(prefixFile);
List<String> inline = read(inlineFile);
List<String> suffix = read(productFile);
String fileText = interleave(prefix, inline, suffix);
//write the single string to file however you want
} catch (...) {...}//do your error handling...
}
//helper methods and some static variables
private static Scanner reader;//I just prefer scanner. Use whatever you want.
private static StringBuilder sb;
private static List<String> read(String filename) throws IOException
{
List<String> list = new ArrayList<String>;
try (reader = new Scanner(new File(filename)))
{
while(reader.hasNext())
{ list.add(reader.nextLine()); }
} catch (...) {...}//catch errors...
}
//I'm going to build the whole file in one string, but you could also have this method return one line at a time (something like an iterator) and output it to the file to avoid creating the massive string
private static String interleave(List<String> one, List<String> two, List<String> three)
{
sb = new StringBuilder();
for (int i = 0; i < one.size(); i++)//notice no checking on size equality of words or the lists. you might want this
{
sb.append(one.get(i)).append(two.get(i)).append(three.get(i)).append("\n");
}
return sb.toString()
}
Obviously there is still some to be desired in terms of memory and performance; additionally there are ways to make this slightly more extensible to other situations, but it's a good starting point. With c#, I could more easily make use of the iterator to make interleave give you one line at a time, potentially saving memory. Just a different idea!

How would I add a return statement for this, and how do I call the method?

public class InputFileData {
/**
* #param inputFile a file giving the data for an electronic
* equipment supplier’s product range
* #return an array of product details
* #throws IOException
*/
public static Product [] readProductDataFile(File inputFile) throws IOException {
// CODE GOES HERE (input data from a text file and sort into arraylists)
}
readProductDataFile is used to read a text file, and store it in an array of type Product[]. The code provided cannot be changed, I need a way that works with this code. I've managed to make file reading and sorting into array lists work in a different class, but running it in this way is giving me a couple of problems:
1) I can't call the readProductDataFile method from the Main class, as if it can't find the method (it's definitely in the correct package).
2) I can't figure out how to format the return statement, I've tried lots of different things but I just can't see how to store it as array type Product[].
I haven't provided a lot of specific code so far because I don't want the answer to be handed to me on a platter (this is part of an assignment so I don't want other people to straight up do it for me), but would anyone be able to point me in the right direction to solve this?
To give an idea of how I'm doing at the moment, the following test code worked for me:
ElectronicsEquipmentDemo class:
public class ElectronicsEquipmentDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Name inputFile = new Name();
inputFile.privateName();
}
}
Name class:
public class Name {
public String privateName() {
try {
FileReader fr = new FileReader("myOutput.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
char firstLetter = str.charAt(0);
if (firstLetter == 'P') {
String[] list = str.split("/");
Arrays.toString(list);
String fullName = list[1] + " " + list[2] + " " + list[3] + "\n";
System.out.println(fullName);
}
}
br.close();
} catch (IOException e) {
System.out.println("File not found");
}
return null;
}
}
Which reads from a text file and, if the line begins with P, splits into arrays and prints out specified values (although my attempt to add a return statement made it only return the first line, so still struggling there).
This should do it:
public class Name {
public String[] privateName(){
String[] list;
try {
FileReader fr = new FileReader("myOutput.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
char firstLetter = str.charAt(0);
if (firstLetter == 'P'){
list = str.split("/");
//Arrays.toString(list);
String fullName = list[1] + " " + list[2] + " "+ list[3] + "\n";
System.out.println(fullName);
}
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
return list;
}
}
Edit: fixed scoping issue.
Well, for the first problem, only thing I can notice is that your method is static, so be sure you're calling it correctly.
Also, consider if static is really what you want/need.
For the second problem, return list.toArray(new String[list.size()]) should work.

remove '#' symbol from the beginning of the string in java

Sample data in csv file
##Troubleshooting DHCP Configuration
#Module 3: Point-to-Point Protocol (PPP)
##Configuring HDLC Encapsulation
Hardware is HD64570
So i want to get the lines as
#Troubleshooting DHCP Configuratin
Module 3: Point-to-Point Protocol(PPP)
#Configuring HDLC Encapsulation
Hardware is HD64570
I have written sample code
public class ReadCSV {
public static BufferedReader br = null;
public static void main(String[] args) {
ReadCSV obj = new ReadCSV();
obj.run();
}
public void run() {
String sCurrentLine;
try {
br = new BufferedReader(new FileReader("D:\\compare\\Genre_Subgenre.csv"));
try {
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.charAt(0) == '#'){
System.out.println(sCurrentLine);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am getting below error
##Troubleshooting DHCP Configuration
#Module 3: Point-to-Point Protocol (PPP)
##Configuring HDLC Encapsulation
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at example.ReadCSV.main(ReadCSV.java:19)
Please suggest me how to do this?
Steps:
Read the CSV file line by line
Use line.replaceFirst("#", "") to remove the first # from each line
Write the modified lines to an output stream (file or String) which suites you
If the variable s contains the content of the CSV file as String
s = s.replace("##", "#");
will replace all the occurrencies of '##" with '#'
You need something like String line=buffer.readLine()
Check the first character of the line with line.charAt(0)=='#'
Get the new String with String newLine=line.substring(1)
This is a rather trivial question. Rather than do the work for you, I'll outline the steps that you need to take without gifting you the answer.
Read in a file line by line
Take the first line and check if the first character of this line is a # - If it is, create a substring of this line excluding the first character ( or use fileLine.replaceFirst("#", ""); )
Store this line somewhere in an array like data structure or simply replace the current variable with the edited one ( fileLine = fileLine.replaceFirst("#", ""); )
Repeat until no more lines left from file.
If you want to add these changes to the file, simply overwrite the old file with the new lines (e.g. Using a steam reader and setting second parameter to false would overwrite)
Make an attempt and show us what you have tried, people will be more likely to help if they believe you have attempted the problem yourself thoroughly first.
package stackoverflow.q_25054783;
import java.util.Arrays;
public class RemoveHash {
public static void main(String[] args) {
String [] strArray = new String [3];
strArray[0] = "##Troubleshooting DHCP Configuration";
strArray[1] = "#Module 3: Point-to-Point Protocol (PPP)";
strArray[2] = "##Configuring HDLC Encapsulation";
System.out.println("Original array: " + Arrays.toString(strArray));
for (int i = 0; i < strArray.length; i++) {
strArray[i] = strArray[i].replaceFirst("#", "");
}
System.out.println("Updated array: " + Arrays.toString(strArray));
}
}
//Output:
//Original array: [##Troubleshooting DHCP Configuration, #Module 3: Point-to-Point Protocol (PPP), ##Configuring HDLC Encapsulation]
//Updated array: [#Troubleshooting DHCP Configuration, Module 3: Point-to-Point Protocol (PPP), #Configuring HDLC Encapsulation]
OpenCSV reads CSV file line by line and gives you an array of strings, where each string is one comma separated value, right? Thus, you are operating on a string.
You want to remove '#' symbol from the beginning of the string (if it is there). Correct?
Then this should do it:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine[0].charAt(0) == '#') {
nextLine[0] = nextLine[0].substring(1, nextLine[0].length());
}
}
Replacing the first '#' symbol on each of the lines in the CSV file.
private List<String> getFileContentWithoutFirstChar(File f){
try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(f), Charset.forName("UTF-8")))){
List<String> lines = new ArrayList<String>();
for(String line = input.readLine(); line != null; line = input.readLine()) {
lines.add(line.substring(1));
}
return lines
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
return null;
}
}
private void writeFile(List<String> lines, File f){
try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8))){
for(String line : lines){
bw.write(content);
}
bw.flush();
}catch (Exception e) {
e.printStackTrace();
}
}
main(){
File f = new File("file/path");
List<Stirng> lines = getFileContent(f);
f.delete();
writeFile(lines, f);
}

Categories

Resources